I am building a private file upload site. Alice uploads a file, Bob downloads it.
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.
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)
But how do I get this to work in Django? A views function should return a HTTPResponse object, which this doesn't do.
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.
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.
See: 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/
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.