django generate and download a CSV file

First, generate small csv file

1, direct data processing

from django.utils.httpwrappers Import the HttpResponse
 Import csv 

# simple csv file download generate 
DEF down_csv_1 (Request):
     # specified type is returned csv 
    Response = the HttpResponse (the content_type = ' text / csv ' )
     # add instructions how to handle the return header return the object, and specify the file name. attachment: an attachment downloaded as 
    Response [ ' the Content-Disposition ' ] = " Attachment; filename = 'test.csv' " 
    # create a write object 
    Writer = csv.writer (Response)
     # writes a line data 
    writer.writerrow ( [ ' username ', ' Age ' ])
     # write the next row 
    writer.writerrow ([ ' Xsan ' , 20 is ])
     return Response


2, the use of templates to download data processing:

(1) In the process of creating templates folder below the template file data such as test.txt.
test.txt file

{ # Sure to loop and for statements on one line, otherwise the situation will appear blank line} # 
{% for Row in rows row.0%} {{}}, {{row.1 }} 
{ % endfor% }

(2) In view of the function reference

the views.py
 from django.utils.httpwrappers Import the HttpResponse
 from the django.template Import Loader
 Import CSV 

# a stencil process data to be downloaded 
DEF down_csv_2 (Request):
     # type of the return for the CSV 
    Response = the HttpResponse (the content_type = ' text / CSV ' )
     # add instructions on how to return the head to return to deal with this subject, and specify the file name. attachment: an attachment downloaded as 
    Response [ ' the Content-Disposition ' ] = " Attachment; filename = 'test.csv' " 
    # Create data to be downloaded, and a stencil at this time to combine 
    context = {
         'rows ' : [ 
        [ ' username ' , ' Age ' ], 
        [ ' Xsan ' , 20 is ]] 
    } 
    # referenced custom templates 
    Template loader.get_template = ( ' test.txt ' )
     # data format template used to download 
    = csv_template template.render (context)
     # sends the processed data to the rendering context 
    response.content = csv_template
     return Response

Second, generate large csv file
above, we are talking about the generation of a small csv file, if you want to generate a large csv file going to help them? The above code might timeout occurs (server to generate a large csv file, the time required may exceed the browser's default time). At this time we need the help of a class StreamingHttpResponse objects, data objects can respond to this as a stream back to the client, rather than as a whole returned.
About StreamingHttpResponse:
designed to stream data when the class. So that when dealing with large files, because the server will not process too long and lead to connection timeout. This class is not inherited from HttpResponse, and has the following differences with contrast HttpResponse:
1, this class does not attribute content, the opposite is streaming_content.
2, this class is a must streaming_content iterable.
3, this class does not write method, if writing to the data objects of this class will be given.
Note: StreamingHttpResponse will start a process to maintain a long connection and the client, so it will consume resources. So if not special requirements, minimize the use of this method.

    views.py
    from django.http import HttpResponse,StreamingHttpResponse 
    from django.template import loader
    import csv
    
    def large_csv_view(request):
        response = StreamingHttpResponse(content_type='text/csv')
        response['Content-Disposition'] = "attachment;filename='large.csv'"
        rows = ("Row {},{}\n".format(row,row) for row in range(0,10000))
        response.streaming_content = ("username,age\n","Xsan,20\n")
        return response

Guess you like

Origin www.cnblogs.com/xshan/p/12173862.html