zoukankan      html  css  js  c++  java
  • django 从零开始 13 返回文件

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

    # image
    def image(request):
        f = open(r'C:UsersAdministratorDesktop反面.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
  • 相关阅读:
    Drupal 7.23:函数drupal_alter()注释
    请为我们的冷漠付费
    使用Drush管理Drupal站点
    Getting and installing the PEAR package manager
    CKEditor和IMCE构建drupal编辑器
    Drupal资源
    【转】为drupal初学者准备的12个精品课程
    OFBIZ+ECLIPSE
    OFBIZ安装
    CentOS6.4 利用sendEmail发邮件
  • 原文地址:https://www.cnblogs.com/zengxm/p/11332936.html
Copyright © 2011-2022 走看看