|
| 1 | +原文:[Outputting CSV with Django](https://docs.djangoproject.com/en/1.9/howto/outputting-csv/) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +本文解释如何动态的使用Django视图输出CSV (Comma Separated Values)。要做到这点,你可以使用Python CSV库,或者Django模板系统。 |
| 6 | + |
| 7 | + |
| 8 | +## 使用Python CSV库[¶](#using-the-python-csv-library "Permalink to this headline") |
| 9 | + |
| 10 | +Python自带一个CSV库, [`csv`](https://docs.python.org/3/library/csv.html#module-csv "(in Python v3.5)")。在Django中使用它的关键在于,[`csv`](https://docs.python.org/3/library/csv.html#module-csv "(in Python v3.5)")模块作用于类文件对象的CSV创建能力,以及Django的 [`HttpResponse`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse")对象时类文件对象。 |
| 11 | + |
| 12 | +下面是一个例子: |
| 13 | + |
| 14 | +```py |
| 15 | +import csv |
| 16 | +from django.http import HttpResponse |
| 17 | + |
| 18 | +def some_view(request): |
| 19 | + # Create the HttpResponse object with the appropriate CSV header. |
| 20 | + response = HttpResponse(content_type='text/csv') |
| 21 | + response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' |
| 22 | + |
| 23 | + writer = csv.writer(response) |
| 24 | + writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) |
| 25 | + writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) |
| 26 | + |
| 27 | + return response |
| 28 | +``` |
| 29 | + |
| 30 | +代码和注释应该是自解释的,但有几件事值得一提: |
| 31 | + |
| 32 | +* 响应是一种特殊的MIME类型, _text/csv_。这告诉浏览器,这个文档是一个CSV文件,而不是一个HTML文件。如果不这样做的话,浏览器将可能把输出解析成HTML,这将导致在浏览器窗口中的丑陋且可怕的天书。 |
| 33 | +* 响应有一个额外的`Content-Disposition`头,它包含该CSV文件的名字。这个文件名是任意的;随便你叫它啥都行。它将会被浏览器用于“Save as...” 对话框等等。 |
| 34 | +* 钩挂到CSV生成API是容易的:只要把`response`作为第一个参数传递到`csv.writer`即可。`csv.writer`期望一个类文件对象,而[`HttpResponse`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse")对象满足条件。 |
| 35 | +* 对于你的CSV文件中的每一行,调用`writer.writerow`,给它传递一个可迭代对象,例如列表或元祖。 |
| 36 | +* CSV模块为你处理引号,所以你无需担心转义带有引号或者逗号的字符串。只要把原始字符串传递给`writerow()`,它就会正常工作。 |
| 37 | + |
| 38 | +>在Python 2中处理Unicode |
| 39 | +
|
| 40 | +Python 2的[`csv`](https://docs.python.org/3/library/csv.html#module-csv "(in Python v3.5)")模块不支持Unicode输入。由于Django内部使用Unicode,这意味着从源读取的字符串,例如[`HttpRequest`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpRequest "django.http.HttpRequest") ,存在潜在的问题。有几个选择可以处理这个问题: |
| 41 | + |
| 42 | +* 手动编码所有的Unicode对象到兼容的编码。 |
| 43 | +* 使用[csv模块的示例部分](https://docs.python.org/library/csv.html#examples)中提供的`UnicodeWriter`类。 |
| 44 | +* 使用[python-unicodecsv module](https://github.com/jdunck/python-unicodecsv),它旨在成为[`csv`](https://docs.python.org/3/library/csv.html#module-csv "(在Python v3.5中)")随手可得的替代品,它可以优雅的处理Unicode。 |
| 45 | + |
| 46 | +欲了解更多信息,请参阅[`csv`](https://docs.python.org/3/library/csv.html#module-csv "(in Python v3.5)")模块的Python文档。 |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +### 流式传输大尺寸CSV文件[¶](#streaming-large-csv-files "Permalink to this headline") |
| 51 | + |
| 52 | +当处理生成非常大的响应的视图时,你也许会想要考虑使用Django的[`StreamingHttpResponse`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.StreamingHttpResponse "django.http.StreamingHttpResponse")取而代之。 |
| 53 | + |
| 54 | +例如,通过流式传输需要花费长时间生成的文件,你可以避免负载均衡器在服务器生成响应的时候断掉连接。 |
| 55 | + |
| 56 | +在这个例子中,我们利用Python的生成器来有效处理大尺寸CSV文件的拼接和传输: |
| 57 | +```py |
| 58 | +import csv |
| 59 | + |
| 60 | +from django.utils.six.moves import range |
| 61 | +from django.http import StreamingHttpResponse |
| 62 | + |
| 63 | +class Echo(object): |
| 64 | + """An object that implements just the write method of the file-like |
| 65 | + interface. |
| 66 | + """ |
| 67 | + def write(self, value): |
| 68 | + """Write the value by returning it, instead of storing in a buffer.""" |
| 69 | + return value |
| 70 | + |
| 71 | +def some_streaming_csv_view(request): |
| 72 | + """A view that streams a large CSV file.""" |
| 73 | + # Generate a sequence of rows. The range is based on the maximum number of |
| 74 | + # rows that can be handled by a single sheet in most spreadsheet |
| 75 | + # applications. |
| 76 | + rows = (["Row {}".format(idx), str(idx)] for idx in range(65536)) |
| 77 | + pseudo_buffer = Echo() |
| 78 | + writer = csv.writer(pseudo_buffer) |
| 79 | + response = StreamingHttpResponse((writer.writerow(row) for row in rows), |
| 80 | + content_type="text/csv") |
| 81 | + response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' |
| 82 | + return response |
| 83 | +``` |
| 84 | + |
| 85 | + |
| 86 | +## 使用模板系统[¶](#using-the-template-system "Permalink to this headline") |
| 87 | + |
| 88 | +或者,你也可以使用[_Django模板系统_](https://docs.djangoproject.com/en/1.9/topics/templates/)来生成CSV。这比使用便利的Python [`csv`](https://docs.python.org/3/library/csv.html#module-csv "(在Python v3.5中)")模块更低级别,但出于完整性,这里提出了这个方法。 |
| 89 | + |
| 90 | +这里的想法是,将项列表传递给你的模板,并在一个[`for`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#std:templatetag-for)循环中让模板输出逗号。 |
| 91 | + |
| 92 | +下面是一个例子,它生成如上相同的CSV文件: |
| 93 | + |
| 94 | +```py |
| 95 | +from django.http import HttpResponse |
| 96 | +from django.template import loader, Context |
| 97 | + |
| 98 | +def some_view(request): |
| 99 | + # Create the HttpResponse object with the appropriate CSV header. |
| 100 | + response = HttpResponse(content_type='text/csv') |
| 101 | + response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' |
| 102 | + |
| 103 | + # The data is hard-coded here, but you could load it from a database or |
| 104 | + # some other source. |
| 105 | + csv_data = ( |
| 106 | + ('First row', 'Foo', 'Bar', 'Baz'), |
| 107 | + ('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"), |
| 108 | + ) |
| 109 | + |
| 110 | + t = loader.get_template('my_template_name.txt') |
| 111 | + c = Context({ |
| 112 | + 'data': csv_data, |
| 113 | + }) |
| 114 | + response.write(t.render(c)) |
| 115 | + return response |
| 116 | +``` |
| 117 | + |
| 118 | +这个例子和前面那个例子唯一的区别在于,它使用了模板加载,而不是CSV模块。代码剩余的部分,例如`content_type='text/csv'`, 是一样的。 |
| 119 | + |
| 120 | +然后,创建模板`my_template_name.txt`,如下所示: |
| 121 | +```html |
| 122 | +{% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}" |
| 123 | +{% endfor %} |
| 124 | +``` |
| 125 | + |
| 126 | +这个模板相当基础。它只是遍历提供的数据,然后一行显示一行CSV。它使用[`addslashes`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#std:templatefilter-addslashes)模板过滤器来保证在处理引号的时候不存在任何问题。 |
| 127 | + |
| 128 | + |
| 129 | + |
| 130 | +## 其他基于文本的格式[¶](#other-text-based-formats "Permalink to this headline") |
| 131 | + |
| 132 | +注意,这里并没有很具体到CSV —— 只是特定的输出格式。你可以食用这些技术来输出你能想到的任何基于文本的格式。你也可以使用相似的技术来生成任意的二进制数据;见[_使用Django输出PDF_](https://docs.djangoproject.com/en/1.9/howto/outputting-pdf/)。 |
| 133 | + |
| 134 | + |
0 commit comments