Skip to content

Commit 80e4d18

Browse files
committed
update documents of django
1 parent 5600b00 commit 80e4d18

3 files changed

Lines changed: 584 additions & 0 deletions

File tree

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
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+
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
原文:[Outputting PDFs with Django](https://docs.djangoproject.com/en/1.9/howto/outputting-pdf/)
2+
3+
---
4+
5+
本文解释了如何使用Django视图动态的生成PDF文件。优秀的开源[ReportLab](http://www.reportlab.com/opensource/),这个Python PDF库,使其成为了可能。
6+
7+
动态生成PDF文件的好处是,你可以根据不同的目的(比如,为不同的用户或不同的内容)创建定制的PDF。
8+
9+
例如,[kusports.com](http://www.kusports.com/)就用Django来为参加疯狂三月比赛的人生成定制的、打印友好的,PDF格式的NCAA锦标赛表格。
10+
11+
12+
## 安装ReportLab[](#install-reportlab "Permalink to this headline")
13+
14+
[在PyPI上](https://pypi.python.org/pypi/reportlab),可以找到ReportLab库。还可以下载一份[用户指南](http://www.reportlab.com/docs/reportlab-userguide.pdf) (并不是巧合,它就是一份PDF文件)。你可以通过
15+
`pip`安装ReportLab:
16+
```sh
17+
$ pip install reportlab
18+
```
19+
20+
通过将其导入到Python的交互式解释器来测试安装是否成功:
21+
```py
22+
>>> import reportlab
23+
```
24+
25+
如果这个命令不会引发任何错误,那么说明安装好了。
26+
27+
28+
## 编写视图[](#write-your-view "Permalink to this headline")
29+
30+
使用Django动态生成PDF文件的关键在于,ReportLab API操作的是类文件对象,而Django的[`HttpResponse`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse")对象就是类文件对象。
31+
32+
这里是一个“Hello World”例子:
33+
34+
```py
35+
from reportlab.pdfgen import canvas
36+
from django.http import HttpResponse
37+
38+
def some_view(request):
39+
# Create the HttpResponse object with the appropriate PDF headers.
40+
response = HttpResponse(content_type='application/pdf')
41+
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
42+
43+
# Create the PDF object, using the response object as its "file."
44+
p = canvas.Canvas(response)
45+
46+
# Draw things on the PDF. Here's where the PDF generation happens.
47+
# See the ReportLab documentation for the full list of functionality.
48+
p.drawString(100, 100, "Hello world.")
49+
50+
# Close the PDF object cleanly, and we're done.
51+
p.showPage()
52+
p.save()
53+
return response
54+
```
55+
56+
代码和注释应该是自解释的,但有几件事值得一提:
57+
58+
* window.response有一个特殊的MIME类型,_application/pdf_。它告诉浏览器,该文档是一个PDF文件,而不是一个HTML文件。如果不使用它,浏览器将有可能将输出解析为HTML,这将导致在浏览器窗口中丑陋可怕的鬼画符。
59+
60+
* response有一个额外的`Content-Disposition`头,它包含该PDF文件的名字。这个文件名是可选的:任何你想要的时候使用它。它也被浏览器使用于“Save as...”对话框中。
61+
62+
* 在这个例子中,`Content-Disposition`头以`'attachment; '`开头。这会强制web浏览器弹出一个对话框来提示/确认如何处理该文档,即使在该机器上已经设置了默认值。如果你不用`'attachment;'`,那么浏览器将使用为PDF文件配置的程序/插件来处理该PDF。下面是代码可能的样子:
63+
```py
64+
response['Content-Disposition'] = 'filename="somefilename.pdf"'
65+
```
66+
67+
* 钩挂到ReportLab API是容易的:只要把`response`作为第一个参数传递给`canvas.Canvas`即可。`Canvas`类需要一个类文件对象,而[`HttpResponse`](https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse")对象恰好满足要求。
68+
69+
* 注意,所有后继的PDF生成方法都是由该PDF对象(在这个例子中是`p`)调用的,而不是`response`。
70+
71+
* 最后,在该PDF文件上调用`showPage()`和`save()`很重要。
72+
73+
>注意
74+
75+
>ReportLab并不是线程安全的。我们的一些用户已经报告了在构建同时由多人访问的PDF生成的Django视图时出现的奇怪的问题。
76+
77+
78+
## 复杂的PDF文件[](#complex-pdfs "Permalink to this headline")
79+
80+
如果你正在用ReportLab创建一个复杂的PDF文档,那么考虑一下使用[`io`](https://docs.python.org/3/library/io.html#module-io "(in Python v3.5)")库作为临时保存你的PDF文件的地方。这个库提供了一个非常有效的类文件对象接口。这里是上面的“Hello World”例子改写为使用[`io`](https://docs.python.org/3/library/io.html#module-io "(in Python v3.5)")的代码:
81+
```py
82+
from io import BytesIO
83+
from reportlab.pdfgen import canvas
84+
from django.http import HttpResponse
85+
86+
def some_view(request):
87+
# Create the HttpResponse object with the appropriate PDF headers.
88+
response = HttpResponse(content_type='application/pdf')
89+
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
90+
91+
buffer = BytesIO()
92+
93+
# Create the PDF object, using the BytesIO object as its "file."
94+
p = canvas.Canvas(buffer)
95+
96+
# Draw things on the PDF. Here's where the PDF generation happens.
97+
# See the ReportLab documentation for the full list of functionality.
98+
p.drawString(100, 100, "Hello world.")
99+
100+
# Close the PDF object cleanly.
101+
p.showPage()
102+
p.save()
103+
104+
# Get the value of the BytesIO buffer and write it to the response.
105+
pdf = buffer.getvalue()
106+
buffer.close()
107+
response.write(pdf)
108+
return response
109+
```
110+
111+
## 更多资源[](#further-resources "Permalink to this headline")
112+
113+
* [PDFlib](http://www.pdflib.org/)是另外一个具有Python绑定的PDF生成库。要在Django中使用它,只要使用在这篇文章中解释的相同概念即可。
114+
* [XHTML2PDF](https://github.com/xhtml2pdf/xhtml2pdf)是另外一个PDF生成库。它自带了一个如何集成到Django的例子。
115+
* [HTMLdoc](https://www.msweet.org/projects.php?Z1) 是一个命令行脚本,它可以将HTML转换成PDF。它并没有一个Python接口,但是你可以使用`system`或者`popen`来跳出到shell方式,然后在Python中检索输出。
116+
117+
## 其他格式[](#other-formats "Permalink to this headline")
118+
119+
请注意,这些例子中并没有很多是PDF特有的 —— 只是使用`reportlab`的一小部分。你可以使用类似的技术来生成任意你可以找到Python库来生成的格式。另见[_使用Django输出CSV_](./使用Django输出CSV.md),以获得另一个例子,以及一些在生成基于文本的格式时可以使用的技术。
120+

0 commit comments

Comments
 (0)