某些时候可能有这样的需求,在网页中点击一个链接或者一个按钮希望返回一张图片、一个pdf文档、一个csv文档等而非html。在diango中很容易做到这些。django中的view用来接收http request并返回web response。通常情况下,返回的内容为html,但其能够返回的不仅仅如此,还可以是上述图片、pdf文件等等。返回非html形式的内容的关键在于httpresponse这个类,尤其是mimetype这个参数,通过将此参数设置为不同的值可以提示浏览器view返回了不同格式的内容。比如,想要返回图片内容,只需读如一张图片,然后在httpresponse中指明图片的mimetype并将图片内容作为另一参数response给浏览器,浏览器能够自动正确的显示图片内容。
from django.http import httpresponsedef my_image(request): image_data = open(/path/to/my/image.png, rb).read() return httpresponse(image_data, mimetype=image/png)
另外一个需要特别注意的的是httpresponse对象实现了python的标准“file-like-object”api,也即可以将httpresponse当做文件使用。
例子:
生成csv格式的内容
import csvfrom django.http import httpresponse# number of unruly passengers each year 1995 - 2005. in a real application# this would likely come from a database or some other back-end data store.unruly_passengers = [146,184,235,200,226,251,299,273,281,304,203]def unruly_passengers_csv(request): # create the httpresponse object with the appropriate csv header. response = httpresponse(mimetype='text/csv') response['content-disposition'] = 'attachment; filename=unruly.csv' # create the csv writer using the httpresponse as the file. writer = csv.writer(response) writer.writerow(['year', 'unruly airline passengers']) for (year, num) in zip(range(1995, 2006), unruly_passengers): writer.writerow([year, num]) return response
需要注意的几点:
1.httpresponse中mimetype指定为了'text/csv'告知浏览器返回的文档是csv文件。
2.httpresponse设置了另外一个参数content-disposition其中attachment告知浏览器保存返回的文档而非显示其内容,filename指明了返回文档的名字,改名字可任意指定。
3.因为csv的writer方法期望一个文件类型的对象作为参数,而httpresponse实例可以当做文件使用,所以可以直接在csv模块的writer方法中将httpresponse作为参数。
4.writer.writerow方法负责往文件中写入一行内容。
上述方法是返回非html格式内容的通用模式,也即:创建一个特定mime type的httpresponse,将其传递给以文件为参数产生特定格式的文档的方法,之后返回该response。
生成pdf格式的内容
from reportlab.pdfgen import canvasfrom django.http import httpresponsedef hello_pdf(request): # create the httpresponse object with the appropriate pdf headers. response = httpresponse(mimetype='application/pdf') response['content-disposition'] = 'attachment; filename=hello.pdf' # create the pdf object, using the response object as its file. p = canvas.canvas(response) # draw things on the pdf. here's where the pdf generation happens. # see the reportlab documentation for the full list of functionality. p.drawstring(100, 100, hello world.) # close the pdf object cleanly, and we're done. p.showpage() p.save() return response
流程基本同上,需要注意的几点:
1.此处使用了 application/pdf mime type告知浏览器返回的是pdf文件,而非html,否则浏览器会将其作为普通html内容处理。
2.canvas.canvas方法期望一个file-like的对象作为参数,将httpresponse传递给该方法。
3.使用canvas实例的方法绘制pdf文档,调用showpage()方法和save()方法(否则会产生损坏的pdf文档)。
4.最后返回该httpresponse实例
生成更为复杂的pdf文档,这里使用了cstringio库来临时存放pdf文件
from cstringio import stringiofrom reportlab.pdfgen import canvasfrom django.http import httpresponsedef hello_pdf(request): # create the httpresponse object with the appropriate pdf headers. response = httpresponse(mimetype='application/pdf') response['content-disposition'] = 'attachment; filename=hello.pdf' temp = stringio() # create the pdf object, using the stringio object as its file. p = canvas.canvas(temp) # draw things on the pdf. here's where the pdf generation happens. # see the reportlab documentation for the full list of functionality. p.drawstring(100, 100, hello world.) # close the pdf object cleanly. p.showpage() p.save() # get the value of the stringio buffer and write it to the response. response.write(temp.getvalue()) return response
其他可能的格式
实质上,任何可以写文件的python库都可与django的httpresponse结合用以返回特定格式的内容,如zip文件、动态图片、图表、xls文件等等。
最后在看一个返回xls文件的例子
from django.http import httpresponseimport xlwtdef viewxls(request): response = httpresponse(mimetype='application/vnd.ms-excel') response['content-disposition'] = 'attachment; filename=request.xls' book = xlwt.workbook(encoding='utf8') sheet = book.add_sheet('untitled') for row, column, value in ((0,0,1),(0,1,2),(1,0,3),(1,1,4)) sheet.write(int(row),int(column),value) book.save(response) return response
流程同上,不在注释。
另外,需要特别注意的是,这里的request必须是通过表单提交才能正确返回特定格式的内容,若要是通过ajax方式发起的request则返回的内容会被当做文本串处理,而不能被浏览器解释为特定内容。
比如: $.ajax({ url:{% url 'mycitsm.views.viewxls' %}, data:postdata, type:post, success:function(result){ }, });//是不可以的,而要使用如下的表单提交才可以:var form = $(#xlsform);form.attr({ action:{% url 'mycitsm.views.returnxls' %}, method:post });form.submit();
说到这里有必要记录一下开发过程中遇到的一个问题,也即将表单内容序列化为字符串的问题。
有时需将表单中的所有内容序列化为键值对构成的串做为一个整体进行url参数传递,而且需要对值中包含的特殊字符进行编码。比如有如下表单:
4
567
$('form').submit(function() { alert($(this).serialize()); return false;});#可以输出a=1&c=3&d=4&e=5为什么第二个text类型的input的值还有checkbox类型的input的值以及submit类型的input没有被序列化呢?这是因为如果要表单元素的值包含到序列字符串中,元素必须使用 name 属性。而第二个text类型的input无name属性。checkbox类型的input有一个并没有被checked所以……。serialize()只会将”成功的控件“序列化为字符串。如果不使用按钮来提交表单,则不对提交按钮的值序列化,所以submit类型的input没有被序列化。
当然除了直接对整个form序列化外还可对已选取的个别表单元素的jquery对象序列化,如,等等。