Python-让Django提供可下载文件

Python-让Django提供可下载文件,第1张

Python-让Django提供可下载文件

你可以将

S.Lott
的解决方案与
xsendfile
模块结合使用:
django
生成文件(或文件本身)的路径,但是实际的文件服务由
Apache / Lighttpd
处理。设置
mod_xsendfile
后,与视图集成将需要几行代码:

from django.utils.encoding import smart_strresponse = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)response['X-Sendfile'] = smart_str(path_to_file)# It's usually a good idea to set the 'Content-Length' header too.# You can also set any other required headers: Cache-Control, etc.return response

当然,只有在你可以控制服务器或托管公司已经设置了

mod_xsendfile
的情况下,这才起作用。

编辑

django 1.7将mimetype替换为

content_type

response = HttpResponse(content_type='application/force-download'  

编辑: 对于

nginx
检查此,它使用
X-Accel-Redirect
而不是
apacheX-Sendfile
标头。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4971709.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存