Idea Pitch

After I got my feedback I decided that it would be best if I just started over so, that is what I did. I made the background an actual color but, not a distracting one and put a bold color where I…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Streaming a file through Django

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

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.

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?

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

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:

Add a comment

Related posts:

A casa dos 30

Posso falar com autoridade que a casa dos 30 não é um lugar muito confortável pois faz mais de cinco anos que eu moro aqui. Às vezes eu me sinto à vontade, embora as dorzinhas terem começado a me…

How To Find A Job In The Middle East?

Finding a job in the Middle East can be a challenging task, but with the right approach and preparation, it can also be a rewarding experience. The Middle East is a diverse region with a variety of…

Comments on hedgehog meat

The English name for a hedgehog is “Hedgehog”, which comes from eating them. Hedge in English means hedgehog, and Hog means pig. The hedgehogs are used to going under the rivets and finding their…