PageRenderTime 243ms CodeModel.GetById 81ms app.highlight 5ms RepoModel.GetById 156ms app.codeStats 0ms

/django/contrib/staticfiles/handlers.py

https://code.google.com/p/mango-py/
Python | 68 lines | 53 code | 6 blank | 9 comment | 1 complexity | 77f45708bd494357ff77d098543523bb MD5 | raw file
 1import urllib
 2from urlparse import urlparse
 3
 4from django.conf import settings
 5from django.core.handlers.wsgi import WSGIHandler
 6
 7from django.contrib.staticfiles import utils
 8from django.contrib.staticfiles.views import serve
 9
10class StaticFilesHandler(WSGIHandler):
11    """
12    WSGI middleware that intercepts calls to the static files directory, as
13    defined by the STATIC_URL setting, and serves those files.
14    """
15    def __init__(self, application, base_dir=None):
16        self.application = application
17        # Always call get_base_dir() to give subclasses control
18        self.base_dir = self.get_base_dir(base_dir)
19        self.base_url = urlparse(self.get_base_url())
20        super(StaticFilesHandler, self).__init__()
21
22    def get_base_dir(self, base_dir=None):
23        if base_dir: return base_dir
24        return settings.STATIC_ROOT
25
26    def get_base_url(self):
27        utils.check_settings()
28        return settings.STATIC_URL
29
30    def _should_handle(self, path):
31        """
32        Checks if the path should be handled. Ignores the path if:
33
34        * the host is provided as part of the base_url
35        * the request's path isn't under the media path (or equal)
36        """
37        return (self.base_url[2] != path and
38            path.startswith(self.base_url[2]) and not self.base_url[1])
39
40    def file_path(self, url):
41        """
42        Returns the relative path to the media file on disk for the given URL.
43        """
44        relative_url = url[len(self.base_url[2]):]
45        return urllib.url2pathname(relative_url)
46
47    def serve(self, request):
48        """
49        Actually serves the request path.
50        """
51        return serve(request, self.file_path(request.path), insecure=True)
52
53    def get_response(self, request):
54        from django.http import Http404
55
56        if self._should_handle(request.path):
57            try:
58                return self.serve(request)
59            except Http404, e:
60                if settings.DEBUG:
61                    from django.views import debug
62                    return debug.technical_404_response(request, e)
63        return super(StaticFilesHandler, self).get_response(request)
64
65    def __call__(self, environ, start_response):
66        if not self._should_handle(environ['PATH_INFO']):
67            return self.application(environ, start_response)
68        return super(StaticFilesHandler, self).__call__(environ, start_response)