This article mainly introduces the python in the Django framework with streaming response to generate a CSV file tutorial, the author specifically mentioned to prevent the CSV file in Chinese to avoid garbled problems, the need for friends can refer to the
In Django, the streaming response streaminghttpresponse is a good thing to produce a large file quickly and save memory.
One of the current projects for streaming response is EventSource, which is used to improve the slow sense of user-generated communication across systems. This is not to elaborate.
Another is to generate a large CSV file.
When the Django process is in a web container such as Gunicorn or UWSGI, if the response does not return for more than a certain amount of time, it is terminated by the Web container, although we can bypass the problem by adding a time-out to the Web container, but after all, the symptom is not the root cause. To fundamentally solve this problem, the Python generator, the Django framework provides streaminghttpresponse this streaming response is helpful
And in the CSV, Chinese processing is also important, to ensure that the use of Excel to open a CSV is not garbled or something. To save space, I posted all the code together. Actual use according to the project plan to place ha
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The||/tr>|
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22||From django.views.generic import View from django.http.response Import Streaminghttpresponse class Exampleview (View): he aders=[' some ', ' header '] def get (self,request): result = [[' First line ', ' Data 1 '], [' Second row ', ' Data 2 ']] Echoer = Echo () writer = unicodewriter (ec Hoer def csv_itertor (): Yield codecs. Bom_utf8 yield Writer.writerow (self.headers) for column in Result:yield writer.writerow (column) response = Streaminghtt Presponse (row for row in Csv_itertor ()), content_type= "Text/csv;charset=utf-8") response[' content-disposition '] = ' Attachment;filename= "Example.csv" ' return response|
Note < > : More Wonderful tutorials please focus on Triple programming