如何在 Django 中发送文件到响应?

问题描述 投票:0回答:5

我有这样的 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
python django python-2.7 django-1.11
5个回答
23
投票

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

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

阅读文档以获取更多信息: 告诉浏览器将响应视为文件附件返回错误


3
投票

要在 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/generate-and-returning-pdf-as-response-in-django/


1
投票

如果您想返回图像,请不要忘记将其格式化为 png 或 jpeg 并使用 getvalue() 返回字节

img = "Suppose I am a pil image"
fomatted_img = BytesIO()
img.save(fomatted_img, format="png")
response = HttpResponse(fomatted_img.getvalue(),content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
return response

或者您可以将格式化的图像直接保存到响应中

img = "Suppose I am a pil image"
response = HttpResponse(content_type='image/png')
response['Content-Disposition'] = 'attachment; filename="output.png"'
img.save(response,"PNG")
return response

0
投票

Django 有一个

FileResponse
类,它在其构造函数中接受 IO 对象。所以在你看来:

buffer = BytesIO(excel.blob)
response = FileResponse(buffer, as_attachment=True, filename=excel.name)
response["Content-Type"] = "application/vnd.ms-excel"
return response

0
投票
from django.http import FileResponse
def download_file():
  return FileResponse(open('/path/to/file','rb'),
                        filename=file_name,
                        as_attachment=True,
                        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        status=status,
                        )

注意: 内容类型应根据您尝试发送的文件类型进行设置。这里设置的值是针对excel类型的文件

© www.soinside.com 2019 - 2024. All rights reserved.