进行一些操作返回文件,flask和django差不多,基本都是在返回response 并且对其中的返回头部写入返回文件信息

 

# image
def image(request):
    f = open(r'C:\Users\Administrator\Desktop\反面.jpg','rb').read()
    return HttpResponse(f,content_type='image/jpg')


# csv
import csv
UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]
def to_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=ceshi.csv' # 下载csv文件名设置filename b不能中文

    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

# pdf
from reportlab.pdfgen import canvas
def to_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=ceshi_pdf.pdf'

    p = canvas.Canvas(response)

    p.drawString(500, 200, "Hello world.")   # 和csv一样,坐标位置是从左下角开始的

    p.showPage()
    p.save()
    return response



# 对大型文件进行一个内存操作,如果内容不大,可以使用上面的办法
from io import BytesIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def to_max_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=ceshi_max.pdf'

    temp = BytesIO()           #BytesIO是编码内容保存在内存中

    p = canvas.Canvas(temp)

    p.drawString(100, 100, "Hello world.")

    p.showPage()
    p.save()                    

    response.write(temp.getvalue())
    return response