Django:让用户下载大文件 [英] Django: let user download a large file
问题描述
我正在建立一个私人文件上传站点.爱丽丝上传文件,鲍勃下载文件.
I am building a private file upload site. Alice uploads a file, Bob downloads it.
爱丽丝(Alice)和鲍勃(Bob)之外的其他人不应具有访问权限.我最初是在考虑为文件提供一个复杂的名称(http://domain/download/md5sum.zip
),但是我想要一个过期的链接.像http://domain/download/tempkey/aaa123/file.zip
这样的东西.这将使我可以更好地控制文件的下载和日志记录.
People other than Alice and Bob should not have access. I was first thinking about giving the file a complex name ( http://domain/download/md5sum.zip
), but I want an expiring link. So something like http://domain/download/tempkey/aaa123/file.zip
. This will give me more control over file downloading and logging.
我发现了这一点: https://stackoverflow.com/a/2900646 .建议如下:
I found this: https://stackoverflow.com/a/2900646 . It suggests the following:
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
# The URL the client requested
print self.path
# analyze self.path, map the local file location...
# open the file, load the data
with open('test.py') as f: data = f.read()
# send the headers
self.send_response(200)
self.send_header('Content-type', 'application/octet-stream') # you may change the content type
self.end_headers()
# If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.
# wfile is a file-like object. writing data to it will send it to the client
self.wfile.write(data)
但是如何在Django中使用它呢?视图函数应该返回一个HTTPResponse对象,但不会这样做.
But how do I get this to work in Django? A views function should return a HTTPResponse object, which this doesn't do.
推荐答案
实际上不建议使用Django下载大文件.通常,您会拥有一个前端复用器(例如NginX),并仅使用Django来验证文件.
Using Django to download large files isn't really recommended. Usually you'd have a front-end multiplexer such as NginX, and use Django only to validate the file.
然后,如果下载经过验证,您将向多路复用器发出信号.对于NginX,您可以设置一个特殊的标头("X-Accel-Redirect")以指向本地文件的真实位置. Django将只提供几个字节,所有繁重的工作将由NginX承担;同时原始URL将是Django的URL,因此无法绕过安全性.
Then, if the download is validated, you'd issue a signal to the multiplexer. For NginX, you can set up a special header ("X-Accel-Redirect") to point to the true location of the local file. Django will only serve a few bytes, and all the heavy lifting will be taken up by NginX; at the same time the original URL will be that of Django, so that it is not possible to bypass security.
请参阅: http://wiki.nginx.org/X-accel
您可以在此处找到有关如何提供静态文件(可通过身份验证扩展)的注释
You can find notes on how to serve static files (extensible with authentication) here
https://docs.djangoproject.com/en/dev/howto/static-files/
但是正如页面上所说,它是"快速而肮脏的帮助程序视图",不适用于生产或高流量站点.即使Django 可以做到这一点,这也不是Django的初衷.
but as the page says, it is "a quick and dirty helper view" not intended for production or high-traffic sites. That's not what Django was designed to do, even if it can do it.
这篇关于Django:让用户下载大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!