Debian Codegraph @

django/contrib/staticfiles/handlers.py

raw
1 from urllib.parse import urlparse
2 from urllib.request import url2pathname
3
4 from asgiref.sync import sync_to_async
5
6 from django.conf import settings
7 from django.contrib.staticfiles import utils
8 from django.contrib.staticfiles.views import serve
9 from django.core.handlers.asgi import ASGIHandler
10 from django.core.handlers.exception import response_for_exception
11 from django.core.handlers.wsgi import WSGIHandler, get_path_info
12 from django.http import Http404
13
14
15 class StaticFilesHandlerMixin:
16 """
17 Common methods used by WSGI and ASGI handlers.
18 """
19
20 # May be used to differentiate between handler types (e.g. in a
21 # request_finished signal)
22 handles_files = True
23
24 def load_middleware(self):
25 # Middleware are already loaded for self.application; no need to reload
26 # them for self.
27 pass
28
29 def get_base_url(self):
30 utils.check_settings()
31 return settings.STATIC_URL
32
33 def _should_handle(self, path):
34 """
35 Check if the path should be handled. Ignore the path if:
36 * the host is provided as part of the base_url
37 * the request's path isn't under the media path (or equal)
38 """
39 return path.startswith(self.base_url.path) and not self.base_url.netloc
40
41 def file_path(self, url):
42 """
43 Return the relative path to the media file on disk for the given URL.
44 """
45 relative_url = url.removeprefix(self.base_url.path)
46 return url2pathname(relative_url)
47
48 def serve(self, request):
49 """Serve the request path."""
50 return serve(request, self.file_path(request.path), insecure=True)
51
52 def get_response(self, request):
53 try:
54 return self.serve(request)
55 except Http404 as e:
56 return response_for_exception(request, e)
57
58 async def get_response_async(self, request):
59 try:
60 return await sync_to_async(self.serve, thread_sensitive=False)(request)
61 except Http404 as e:
62 return await sync_to_async(response_for_exception, thread_sensitive=False)(
63 request, e
64 )
65
66
67 class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler):
68 """
69 WSGI middleware that intercepts calls to the static files directory, as
70 defined by the STATIC_URL setting, and serves those files.
71 """
72
73 def __init__(self, application):
74 self.application = application
75 self.base_url = urlparse(self.get_base_url())
76 super().__init__()
77
78 def __call__(self, environ, start_response):
79 if not self._should_handle(get_path_info(environ)):
80 return self.application(environ, start_response)
81 return super().__call__(environ, start_response)
82
83
84 class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler):
85 """
86 ASGI application which wraps another and intercepts requests for static
87 files, passing them off to Django's static file serving.
88 """
89
90 def __init__(self, application):
91 self.application = application
92 self.base_url = urlparse(self.get_base_url())
93
94 async def __call__(self, scope, receive, send):
95 # Only even look at HTTP requests
96 if scope["type"] == "http" and self._should_handle(scope["path"]):
97 # Serve static content
98 # (the one thing super() doesn't do is __call__, apparently)
99 return await super().__call__(scope, receive, send)
100 # Hand off to the main app
101 return await self.application(scope, receive, send)
102
103 async def get_response_async(self, request):
104 response = await super().get_response_async(request)
105 response._resource_closers.append(request.close)
106 # FileResponse is not async compatible.
107 if response.streaming and not response.is_async:
108 _iterator = response.streaming_content
109
110 async def awrapper():
111 for part in await sync_to_async(list)(_iterator):
112 yield part
113
114 response.streaming_content = awrapper()
115 return response