【问题标题】:How to send file to response in Django?如何在 Django 中发送文件以响应?
【发布时间】:2018-11-01 22:30:08
【问题描述】:

我有这样的 php 函数,我尝试在我的 Django 项目中重写它。对于像header()show_error() 这样的php 方法,python 中应该有什么类似物?还有如何发送文件响应?

php:

function waprfile($date=false) {
    if(!isset($date) || $date==false) $date = date("d.m.y");

    $timestmp = date2timestamp($date);

    $filepath = "https://www.example.com/files/".$this->lang_code."/";

    if(file_get_contents($filepath.date("dmy",$timestmp).".xls"))
    {
        header("Location: ".$filepath."wapr".date("dmy",$timestmp).".xls");
    }
    else
    {
        show_error(_langWrite("No file for specified date", "Файл на указанную дату отсутствует"));
    }
}

蟒蛇:

import urllib.request
import datatime
import time
from django.utils import translation

def isset(variable):
    return variable in locals() or variable in globals()

def waprfile(request, date):
    if(not isset(date) or date==False):
        date = datetime.datetime.now().strftime('%d.%m.%Y')

    timestmp = time.mktime(datatime.datetime.strptime(date, "%d.%m.%Y").timetuple())

    filepath = "https://www.example.com/files/" + str(translation.get_language()) + "/"

    formatted_date = datetime.datetime.fromtimestamp(timestmp).strftime('%d%m%y')

    if(urllib.request.urlopen(filepath + formatted_date + '.xls')):
        # What must be here?
    else:
        # What must be here?

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=' + fileName
    return response

【问题讨论】:

    标签: php python django python-2.7 django-1.11


    【解决方案1】:

    先读取文件,然后发送响应。

    from django.http import HttpResponse, HttpResponseNotFound
    
    def waprfile(request, date):
        ...
    
        file_location = '/path/to/file/foo.xls'
    
        try:    
            with open(file_location, 'r') as f:
               file_data = f.read()
    
            # sending response 
            response = HttpResponse(file_data, content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename="foo.xls"'
    
        except IOError:
            # handle file not exist case here
            response = HttpResponseNotFound('<h1>File not exist</h1>')
    
        return response
    

    阅读文档了解更多信息: telling browser to treat the response as a file attachmentreturning errors

    【讨论】:

    • 谢谢!我能再问一个问题吗?假设当我们尝试打开不存在的文件时,我们需要发送什么响应?
    • 在这种情况下,您必须发送 JSON 响应或 HTML 响应,说明文件不存在。
    • 如果我使用response = HttpResponse(status=204),你怎么看?
    • 204 表示请求成功,响应正文中没有要发送的内容,这完全取决于您的用例,您可以发送错误或成功响应
    • 有没有什么包可以轻松做到这一点?
    【解决方案2】:

    要在 Django 中返回 PDF 文件作为响应,请使用以下代码。

    def index(request):
        data = dict()
        data["name"] = "https://www.pythoncircle.Com"
        data["DOB"] = "Jan 10, 2015"
    
        template = get_template('testapp/test.html')
        html = template.render(data)
        pdf = pdfkit.from_string(html, False)
    
        filename = "sample_pdf.pdf"
    
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
        return response
    

    [1]https://www.pythoncircle.com/post/470/generating-and-returning-pdf-as-response-in-django/

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 2021-07-10
      • 2020-03-03
      • 1970-01-01
      • 2021-02-06
      • 2021-01-17
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多