outputting-csv.txt 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. ========================
  2. How to create CSV output
  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(
  18. content_type="text/csv",
  19. headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'},
  20. )
  21. writer = csv.writer(response)
  22. writer.writerow(["First row", "Foo", "Bar", "Baz"])
  23. writer.writerow(["Second row", "A", "B", "C", '"Testing"', "Here's a quote"])
  24. return response
  25. The code and comments should be self-explanatory, but a few things deserve a
  26. mention:
  27. * The response gets a special MIME type, :mimetype:`text/csv`. This tells
  28. browsers that the document is a CSV file, rather than an HTML file. If
  29. you leave this off, browsers will probably interpret the output as HTML,
  30. which will result in ugly, scary gobbledygook in the browser window.
  31. * The response gets an additional ``Content-Disposition`` header, which
  32. contains the name of the CSV file. This filename is arbitrary; call it
  33. whatever you want. It'll be used by browsers in the "Save as..." dialog, etc.
  34. * You can hook into the CSV-generation API by passing ``response`` as the first
  35. argument to ``csv.writer``. The ``csv.writer`` function expects a file-like
  36. object, and :class:`~django.http.HttpResponse` objects fit the bill.
  37. * For each row in your CSV file, call ``writer.writerow``, passing it an
  38. :term:`iterable`.
  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. Pass ``writerow()``
  41. your raw strings, and it'll do the right thing.
  42. .. _streaming-csv-files:
  43. Streaming large CSV files
  44. -------------------------
  45. When dealing with views that generate very large responses, you might want to
  46. consider using Django's :class:`~django.http.StreamingHttpResponse` instead.
  47. For example, by streaming a file that takes a long time to generate you can
  48. avoid a load balancer dropping a connection that might have otherwise timed out
  49. while the server was generating the response.
  50. In this example, we make full use of Python generators to efficiently handle
  51. the assembly and transmission of a large CSV file::
  52. import csv
  53. from django.http import StreamingHttpResponse
  54. class Echo:
  55. """An object that implements just the write method of the file-like
  56. interface.
  57. """
  58. def write(self, value):
  59. """Write the value by returning it, instead of storing in a buffer."""
  60. return value
  61. def some_streaming_csv_view(request):
  62. """A view that streams a large CSV file."""
  63. # Generate a sequence of rows. The range is based on the maximum number of
  64. # rows that can be handled by a single sheet in most spreadsheet
  65. # applications.
  66. rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
  67. pseudo_buffer = Echo()
  68. writer = csv.writer(pseudo_buffer)
  69. return StreamingHttpResponse(
  70. (writer.writerow(row) for row in rows),
  71. content_type="text/csv",
  72. headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'},
  73. )
  74. Using the template system
  75. =========================
  76. Alternatively, you can use the :doc:`Django template system </topics/templates>`
  77. to generate CSV. This is lower-level than using the convenient Python :mod:`csv`
  78. module, but the solution is presented here for completeness.
  79. The idea here is to pass a list of items to your template, and have the
  80. template output the commas in a :ttag:`for` loop.
  81. Here's an example, which generates the same CSV file as above::
  82. from django.http import HttpResponse
  83. from django.template import loader
  84. def some_view(request):
  85. # Create the HttpResponse object with the appropriate CSV header.
  86. response = HttpResponse(
  87. content_type="text/csv",
  88. headers={"Content-Disposition": 'attachment; filename="somefilename.csv"'},
  89. )
  90. # The data is hard-coded here, but you could load it from a database or
  91. # some other source.
  92. csv_data = (
  93. ("First row", "Foo", "Bar", "Baz"),
  94. ("Second row", "A", "B", "C", '"Testing"', "Here's a quote"),
  95. )
  96. t = loader.get_template("my_template_name.txt")
  97. c = {"data": csv_data}
  98. response.write(t.render(c))
  99. return response
  100. The only difference between this example and the previous example is that this
  101. one uses template loading instead of the CSV module. The rest of the code --
  102. such as the ``content_type='text/csv'`` -- is the same.
  103. Then, create the template ``my_template_name.txt``, with this template code:
  104. .. code-block:: html+django
  105. {% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}"
  106. {% endfor %}
  107. This short template iterates over the given data and displays a line of CSV for
  108. each row. It uses the :tfilter:`addslashes` template filter to ensure there
  109. aren't any problems with quotes.
  110. Other text-based formats
  111. ========================
  112. Notice that there isn't very much specific to CSV here -- just the specific
  113. output format. You can use either of these techniques to output any text-based
  114. format you can dream of. You can also use a similar technique to generate
  115. arbitrary binary data; see :doc:`/howto/outputting-pdf` for an example.