Streaming a file through Django

Walid Mani
2 min readApr 3, 2018

--

How to serve a file given its URL through a Django web app to the client?

Solution 1

How about returning the file URL directly to the user? We could return the URL only if the user is authorized to and we could avoid handling the file serving. But what would happen if this user sends this URL to someone else? This doesn’t seems like a viable solution.

Solution 2

Another solution would be to download the file in the server hosting the Django app and then serve it back to the client. But what if the file is too large? and what if multiple users try to download multiple different files at the same time?

Solution 3

A slightly different approach would be to “stream” the file through our Django app if the user is authorized to.

The storage will not be used in our app server and any user will still have to go through our app to download the file. This seems to be an adequate solution so lets implement it!

Here is the code for the view

Download view

Django already handles the default user authorization and you can still handle custom auth.

The file URL can be dynamic and is then downloaded using requests using the keyword arg stream set to True.

Then we create a special type of django response StreamingHttpResponse with the streaming content.

Returning the Streaming directly then would make your browser display the stream!

So we have to add a new field to the response containing the filename to make your browser save the file instead.

That’s it!

References:

--

--

Walid Mani

Software developer and technology enthusiast. Always learning, always discovering