python - Django 提供下载文件

标签 python django file download

我正在尝试提供一个由某些内容生成的 txt 文件,但我遇到了一些问题。我已经创建了临时文件并使用 NamedTemporaryFile 编写了内容,只是将 delete 设置为 false 进行调试,但下载的文件不包含任何内容。

我的猜测是响应值没有指向正确的文件,所以没有下载任何东西,这是我的代码:

    f = NamedTemporaryFile()
    f.write(p.body)

    response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
    response['X-Sendfile'] = f.name

最佳答案

您是否考虑过像这样通过 response 发送 p.body:

response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)

关于python - Django 提供下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15790136/

相关文章:

c#二进制序列化到文件逐行或如何分离

python - 在 2D Python 数字字典中插入值

Python导入MySQLdb : Library not loaded: libmysqlclient. 18.dylib

python - Django iframe : sessionkey being created every request

c# - 在 C# 中使用 FileSystemWatcher 确定复制/写入进度

django - 使用 django + nginx + apache mod_wsgi 访问正在进行的上传文件

javascript - 在 python 中加密 - 在 Javascript 中解密

python - Polars 根据计算添加列抛出 TypeError : 'Expr' object is not subscriptable

python - models.GenericIpAddressField 的默认值

python - 如何在Python中打印没有ASCII字符的字符串?