I found myself needing to write a Django view to serve a file. The path to the file is held in the database, and is not in the URL space, so using Django’s static file stuff isn’t appropriate.
It’s easy once you twig that an
HttpResponse object is a file-like object; just open the source file and copy it to the response object. This was my first attempt:
with open(path, 'rb') as f: response = HttpResponse(mimetype=file.mime_type) copyfileobj(f, response) return response
copyfileobj is from the python
It works, though I was mildly concerned that the copy presumably causes the whole file to be read into memory before being served, rather than being written directly down the socket to the client. There is a more elegant way to do it:
f = open(path, 'rb')return HttpResponse(content=f, mimetype=file.mime_type)
Since a Python
File object is an iterable, and
content can be an iterable or a string, this works. What I’m not sure about, though, is when or how the file
f gets closed.