PageRenderTime 145ms CodeModel.GetById 0ms RepoModel.GetById 0ms 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
Possible License(s): BSD-3-Clause
  1. import urllib
  2. from urlparse import urlparse
  3. from django.conf import settings
  4. from django.core.handlers.wsgi import WSGIHandler
  5. from django.contrib.staticfiles import utils
  6. from django.contrib.staticfiles.views import serve
  7. class StaticFilesHandler(WSGIHandler):
  8. """
  9. WSGI middleware that intercepts calls to the static files directory, as
  10. defined by the STATIC_URL setting, and serves those files.
  11. """
  12. def __init__(self, application, base_dir=None):
  13. self.application = application
  14. # Always call get_base_dir() to give subclasses control
  15. self.base_dir = self.get_base_dir(base_dir)
  16. self.base_url = urlparse(self.get_base_url())
  17. super(StaticFilesHandler, self).__init__()
  18. def get_base_dir(self, base_dir=None):
  19. if base_dir: return base_dir
  20. return settings.STATIC_ROOT
  21. def get_base_url(self):
  22. utils.check_settings()
  23. return settings.STATIC_URL
  24. def _should_handle(self, path):
  25. """
  26. Checks if the path should be handled. Ignores the path if:
  27. * the host is provided as part of the base_url
  28. * the request's path isn't under the media path (or equal)
  29. """
  30. return (self.base_url[2] != path and
  31. path.startswith(self.base_url[2]) and not self.base_url[1])
  32. def file_path(self, url):
  33. """
  34. Returns the relative path to the media file on disk for the given URL.
  35. """
  36. relative_url = url[len(self.base_url[2]):]
  37. return urllib.url2pathname(relative_url)
  38. def serve(self, request):
  39. """
  40. Actually serves the request path.
  41. """
  42. return serve(request, self.file_path(request.path), insecure=True)
  43. def get_response(self, request):
  44. from django.http import Http404
  45. if self._should_handle(request.path):
  46. try:
  47. return self.serve(request)
  48. except Http404, e:
  49. if settings.DEBUG:
  50. from django.views import debug
  51. return debug.technical_404_response(request, e)
  52. return super(StaticFilesHandler, self).get_response(request)
  53. def __call__(self, environ, start_response):
  54. if not self._should_handle(environ['PATH_INFO']):
  55. return self.application(environ, start_response)
  56. return super(StaticFilesHandler, self).__call__(environ, start_response)