Django: Getting Started Transcripts
Chapter: Deploying Django Webapps
Lecture: Protecting media files

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The simplest configuration for media files is for them to be served by the web server
0:05 and with the right settings you just need to point it to a directory. This mechanism means that anyone with the URL
0:11 will be able to get at all the files though. There are a couple ways of making this more restricted.
0:17 You can write a view that does permission controls and then instead of rendering templates, returns the binary file.
0:24 But then you're using Django to serve the media content instead of the web server. It isn't really optimized for this.
0:32 There is an alternative but it depends on what web server you're using.
0:36 There's a specific way to write a view that returns an almost empty response with just a specific http header set.
0:44 The web server sees this header and intercepts it. It doesn't get set down to the browser instead it uses the header to look for
0:51 the appropriate file and serve it from a protected location. You're still writing a view, but now all the view has to do is return a header.
0:59 The web server takes care of the rest. Your view can have all the permission and validation code you need to protect the file
1:06 without having to worry about serializing the media file to the user. The header is server specific. In Apache, it's called X-Sendfile and in nginx,
1:17 it is X-Accel-Redirect. Details about this are beyond the scope of this course but a little googling will get you there or you can do the best thing,
1:27 depend on someone else's code. There are third party libraries that handle all of this one of which is called Django Protected Files.


Talk Python's Mastodon Michael Kennedy's Mastodon