outputting-csv.txt 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. ==========================
  2. Outputting CSV with Django
  3. ==========================
  4. This document explains how to output CSV (Comma Separated Values) dynamically
  5. using Django views. To do this, you can either use the Python CSV library or the
  6. Django template system.
  7. Using the Python CSV library
  8. ============================
  9. Python comes with a CSV library, :mod:`csv`. The key to using it with Django is
  10. that the :mod:`csv` module's CSV-creation capability acts on file-like objects,
  11. and Django's :class:`~django.http.HttpResponse` objects are file-like objects.
  12. Here's an example::
  13. import csv
  14. from django.http import HttpResponse
  15. def some_view(request):
  16. # Create the HttpResponse object with the appropriate CSV header.
  17. response = HttpResponse(content_type='text/csv')
  18. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  19. writer = csv.writer(response)
  20. writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
  21. writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
  22. return response
  23. The code and comments should be self-explanatory, but a few things deserve a
  24. mention:
  25. * The response gets a special MIME type, :mimetype:`text/csv`. This tells
  26. browsers that the document is a CSV file, rather than an HTML file. If
  27. you leave this off, browsers will probably interpret the output as HTML,
  28. which will result in ugly, scary gobbledygook in the browser window.
  29. * The response gets an additional ``Content-Disposition`` header, which
  30. contains the name of the CSV file. This filename is arbitrary; call it
  31. whatever you want. It'll be used by browsers in the "Save as..."
  32. dialogue, etc.
  33. * Hooking into the CSV-generation API is easy: Just pass ``response`` as the
  34. first argument to ``csv.writer``. The ``csv.writer`` function expects a
  35. file-like object, and :class:`~django.http.HttpResponse` objects fit the
  36. bill.
  37. * For each row in your CSV file, call ``writer.writerow``, passing it an
  38. iterable object such as a list or tuple.
  39. * The CSV module takes care of quoting for you, so you don't have to worry
  40. about escaping strings with quotes or commas in them. Just pass
  41. ``writerow()`` your raw strings, and it'll do the right thing.
  42. .. admonition:: Handling Unicode on Python 2
  43. Python 2's :mod:`csv` module does not support Unicode input. Since Django
  44. uses Unicode internally this means strings read from sources such as
  45. :class:`~django.http.HttpRequest` are potentially problematic. There are a
  46. few options for handling this:
  47. * Manually encode all Unicode objects to a compatible encoding.
  48. * Use the ``UnicodeWriter`` class provided in the `csv module's examples
  49. section`_.
  50. * Use the `python-unicodecsv module`_, which aims to be a drop-in
  51. replacement for :mod:`csv` that gracefully handles Unicode.
  52. For more information, see the Python documentation of the :mod:`csv` module.
  53. .. _`csv module's examples section`: http://docs.python.org/2/library/csv.html#examples
  54. .. _`python-unicodecsv module`: https://github.com/jdunck/python-unicodecsv
  55. .. _streaming-csv-files:
  56. Streaming large CSV files
  57. ~~~~~~~~~~~~~~~~~~~~~~~~~
  58. When dealing with views that generate very large responses, you might want to
  59. consider using Django's :class:`~django.http.StreamingHttpResponse` instead.
  60. For example, by streaming a file that takes a long time to generate you can
  61. avoid a load balancer dropping a connection that might have otherwise timed out
  62. while the server was generating the response.
  63. In this example, we make full use of Python generators to efficiently handle
  64. the assembly and transmission of a large CSV file::
  65. import csv
  66. from django.utils.six.moves import range
  67. from django.http import StreamingHttpResponse
  68. class Echo(object):
  69. """An object that implements just the write method of the file-like
  70. interface.
  71. """
  72. def write(self, value):
  73. """Write the value by returning it, instead of storing in a buffer."""
  74. return value
  75. def some_streaming_csv_view(request):
  76. """A view that streams a large CSV file."""
  77. # Generate a sequence of rows. The range is based on the maximum number of
  78. # rows that can be handled by a single sheet in most spreadsheet
  79. # applications.
  80. rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
  81. pseudo_buffer = Echo()
  82. writer = csv.writer(pseudo_buffer)
  83. response = StreamingHttpResponse((writer.writerow(row) for row in rows),
  84. content_type="text/csv")
  85. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  86. return response
  87. Using the template system
  88. =========================
  89. Alternatively, you can use the :doc:`Django template system </topics/templates>`
  90. to generate CSV. This is lower-level than using the convenient Python :mod:`csv`
  91. module, but the solution is presented here for completeness.
  92. The idea here is to pass a list of items to your template, and have the
  93. template output the commas in a :ttag:`for` loop.
  94. Here's an example, which generates the same CSV file as above::
  95. from django.http import HttpResponse
  96. from django.template import loader, Context
  97. def some_view(request):
  98. # Create the HttpResponse object with the appropriate CSV header.
  99. response = HttpResponse(content_type='text/csv')
  100. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  101. # The data is hard-coded here, but you could load it from a database or
  102. # some other source.
  103. csv_data = (
  104. ('First row', 'Foo', 'Bar', 'Baz'),
  105. ('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"),
  106. )
  107. t = loader.get_template('my_template_name.txt')
  108. c = Context({
  109. 'data': csv_data,
  110. })
  111. response.write(t.render(c))
  112. return response
  113. The only difference between this example and the previous example is that this
  114. one uses template loading instead of the CSV module. The rest of the code --
  115. such as the ``content_type='text/csv'`` -- is the same.
  116. Then, create the template ``my_template_name.txt``, with this template code:
  117. .. code-block:: html+django
  118. {% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}"
  119. {% endfor %}
  120. This template is quite basic. It just iterates over the given data and displays
  121. a line of CSV for each row. It uses the :tfilter:`addslashes` template filter to
  122. ensure there aren't any problems with quotes.
  123. Other text-based formats
  124. ========================
  125. Notice that there isn't very much specific to CSV here -- just the specific
  126. output format. You can use either of these techniques to output any text-based
  127. format you can dream of. You can also use a similar technique to generate
  128. arbitrary binary data; see :doc:`/howto/outputting-pdf` for an example.