Django: serving dynamic binary/media content

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 shutil package.)

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.

1 comment
  1. Anonymous said:

    Thank you, I am trying to do something similar and found your second method to be very concise and elegant.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: