Debian Codegraph @

dj_static.py

raw
1 # -*- coding: utf-8 -*-
2
3 import static
4
5 from django.conf import settings
6 from django.core.handlers.wsgi import WSGIHandler
7 from django.contrib.staticfiles.handlers import StaticFilesHandler as DebugHandler
8
9 try:
10 from urllib.parse import urlparse
11 except ImportError: # Python 2
12 from urlparse import urlparse
13 from django.contrib.staticfiles import utils
14
15 try:
16 from django.core.handlers.wsgi import get_path_info
17 except ImportError: # django < 1.7
18 try:
19 from django.core.handlers.base import get_path_info
20 except ImportError: # django < 1.5
21 import sys
22 py3 = sys.version_info[0] == 3
23
24 def get_path_info(environ):
25 """
26 Returns the HTTP request's PATH_INFO as a unicode string.
27 """
28 path_info = environ.get('PATH_INFO', str('/'))
29 # Under Python 3, strings in environ are decoded with ISO-8859-1;
30 # re-encode to recover the original bytestring provided by the web server.
31 if py3:
32 path_info = path_info.encode('iso-8859-1')
33 # It'd be better to implement URI-to-IRI decoding, see #19508.
34 return path_info.decode('utf-8')
35
36
37 class Cling(WSGIHandler):
38 """WSGI middleware that intercepts calls to the static files
39 directory, as defined by the STATIC_URL setting, and serves those files.
40 """
41 def __init__(self, application, base_dir=None, ignore_debug=False):
42 self.application = application
43 self.ignore_debug = ignore_debug
44 if not base_dir:
45 base_dir = self.get_base_dir()
46 self.base_url = urlparse(self.get_base_url())
47
48 self.cling = static.Cling(base_dir)
49 try:
50 self.debug_cling = DebugHandler(application, base_dir=base_dir)
51 except TypeError:
52 self.debug_cling = DebugHandler(application)
53
54 super(Cling, self).__init__()
55
56 def get_base_dir(self):
57 return settings.STATIC_ROOT
58
59 def get_base_url(self):
60 utils.check_settings()
61 return settings.STATIC_URL
62
63 @property
64 def debug(self):
65 return settings.DEBUG
66
67 def _transpose_environ(self, environ):
68 """Translates a given environ to static.Cling's expectations."""
69 environ['PATH_INFO'] = environ['PATH_INFO'][len(self.base_url[2]) - 1:]
70 return environ
71
72 def _should_handle(self, path):
73 """Checks if the path should be handled. Ignores the path if:
74
75 * the host is provided as part of the base_url
76 * the request's path isn't under the media path (or equal)
77 """
78 return path.startswith(self.base_url[2]) and not self.base_url[1]
79
80 def __call__(self, environ, start_response):
81 # Hand non-static requests to Django
82 if not self._should_handle(get_path_info(environ)):
83 return self.application(environ, start_response)
84
85 # Serve static requests from static.Cling
86 if not self.debug or self.ignore_debug:
87 environ = self._transpose_environ(environ)
88 return self.cling(environ, start_response)
89 # Serve static requests in debug mode from StaticFilesHandler
90 else:
91 return self.debug_cling(environ, start_response)
92
93
94 class MediaCling(Cling):
95
96 def __init__(self, application, base_dir=None):
97 super(MediaCling, self).__init__(application, base_dir=base_dir)
98 # override callable attribute with method
99 self.debug_cling = self._debug_cling
100
101 def _debug_cling(self, environ, start_response):
102 environ = self._transpose_environ(environ)
103 return self.cling(environ, start_response)
104
105 def get_base_dir(self):
106 return settings.MEDIA_ROOT
107
108 def get_base_url(self):
109 return settings.MEDIA_URL