Login

Django nginx sendfile example

Author:
sim1234
Posted:
April 17, 2019
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Use nginx sendfile (X-Accel-Redirect) function to serve files but pass traffic through django. Can be used to serve media files only to logged-in users.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# views.py

from django.http import HttpResponse
from django.views.generic import View


class SendfileView(View):
    prefix = ""

    def get(self, request, path):
        response = HttpResponse()
        response["X-Accel-Redirect"] = f"{self.prefix}{path}"
        del response["Content-Type"]
        return response

# urls.py
from django.urls import re_path

urlpatterns = [
    re_path(r"^/media/(?P<path>.*)$", SendfileView.as_view(prefix="/__media__/"))
]

# nginx.conf
server {
        server_name example.com;
        listen 80;
        location /__media__/ {
                internal;
                alias /path/to/your/media/directory/;
        }
	location / {
		proxy_pass http://url.to.your.django:8000;
	}
}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.