1.图片

  1. 核心是HttpResponse对象实现了Python保准的文件应用程序接口API
  2. 指定mimetype参数,改变mime类型,可以通知浏览器将要返回的数据时另一种类型
from django.http import HttpResponse

def my_image(request):
    image_data = open('/path/to/image.png','rb').read()
    return HttpResponse(image_data,mimetype="image/png")

2.csv文件

  1. 响应返回的是text/csv MIME类型(而非默认的text/html),告诉浏览器,返回的文档是csv文件
  2. 响应会有一个附加的Content-Disposition 头部,包含右csv文件的文件名,这个头部会指示浏览器弹出的对话框询问文件存放的位置(而不仅仅是显示).这个文件名是任意的,它会显示在浏览器的另存为对话框中
  3. 要在HttpResponse指定头部信息,只需要把HttpResponse当做字典使用就好了
  4. 创建csv的对象writer是很容易的,将response作为第一个变量传递给csv.writer构造函数,这个构造函数需要一个文件类的对象,HttpResponse正好能达成这个目的
  5. 后面的writer.writerow方法呢就是写一行数据咯
import csv
from django.http import HttpResponse

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

3.总结

在任何需要返回非HTML内容的时候,都需要经过以下几步,创建一个HttpResponse响应对象(需要指定特殊的MIME类型),它传给需要处理文件的函数,然后返回这个响应对象


4.简单pdf

1.安装reportlab模块

pip install reportlab

2.导入软件包,确定安装成功

>>>import reportlab

3.编写试图函数

  1. 我们使用的mime类型是application/pdf,会告诉浏览器这个文档是一个pdf文档,而不是html文档.如果忽略了这个参数,浏览器就可能会把这个文件看成是html文档
  2. 传入reportlab模块的api很简单,只需要将response对象作为canvas.Canvas构造函数的参数传入
  3. 后续的pdf生成方法需要由pdf对象调用
  4. 需要对pdf文件调用showPage()和save()方法,否则pdf文件损坏
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def 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

5.复杂pdf,或者大的数据块

复杂的pdf,或者比较大的数据块,请使用 cStringIO 库存放临时生成的 PDF 文件.cStringIO 提供了一个用 C 编写的类似文件对象的接口,从而可以使系统的效率最高。

from cStringIO import StringIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def 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
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐