PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/django-1.2/django/middleware/common.py

https://gitlab.com/gregtyka/frankenserver
Python | 148 lines | 145 code | 2 blank | 1 comment | 4 complexity | 2818c591ec60effea70be32d15ee544f MD5 | raw file
  1. import re
  2. from django.conf import settings
  3. from django import http
  4. from django.core.mail import mail_managers
  5. from django.utils.http import urlquote
  6. from django.core import urlresolvers
  7. from django.utils.hashcompat import md5_constructor
  8. class CommonMiddleware(object):
  9. """
  10. "Common" middleware for taking care of some basic operations:
  11. - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS
  12. - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
  13. this middleware appends missing slashes and/or prepends missing
  14. "www."s.
  15. - If APPEND_SLASH is set and the initial URL doesn't end with a
  16. slash, and it is not found in urlpatterns, a new URL is formed by
  17. appending a slash at the end. If this new URL is found in
  18. urlpatterns, then an HTTP-redirect is returned to this new URL;
  19. otherwise the initial URL is processed as usual.
  20. - ETags: If the USE_ETAGS setting is set, ETags will be calculated from
  21. the entire page content and Not Modified responses will be returned
  22. appropriately.
  23. """
  24. def process_request(self, request):
  25. """
  26. Check for denied User-Agents and rewrite the URL based on
  27. settings.APPEND_SLASH and settings.PREPEND_WWW
  28. """
  29. # Check for denied User-Agents
  30. if 'HTTP_USER_AGENT' in request.META:
  31. for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
  32. if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
  33. return http.HttpResponseForbidden('<h1>Forbidden</h1>')
  34. # Check for a redirect based on settings.APPEND_SLASH
  35. # and settings.PREPEND_WWW
  36. host = request.get_host()
  37. old_url = [host, request.path]
  38. new_url = old_url[:]
  39. if (settings.PREPEND_WWW and old_url[0] and
  40. not old_url[0].startswith('www.')):
  41. new_url[0] = 'www.' + old_url[0]
  42. # Append a slash if APPEND_SLASH is set and the URL doesn't have a
  43. # trailing slash and there is no pattern for the current path
  44. if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
  45. urlconf = getattr(request, 'urlconf', None)
  46. if (not _is_valid_path(request.path_info, urlconf) and
  47. _is_valid_path("%s/" % request.path_info, urlconf)):
  48. new_url[1] = new_url[1] + '/'
  49. if settings.DEBUG and request.method == 'POST':
  50. raise RuntimeError, (""
  51. "You called this URL via POST, but the URL doesn't end "
  52. "in a slash and you have APPEND_SLASH set. Django can't "
  53. "redirect to the slash URL while maintaining POST data. "
  54. "Change your form to point to %s%s (note the trailing "
  55. "slash), or set APPEND_SLASH=False in your Django "
  56. "settings.") % (new_url[0], new_url[1])
  57. if new_url == old_url:
  58. # No redirects required.
  59. return
  60. if new_url[0]:
  61. newurl = "%s://%s%s" % (
  62. request.is_secure() and 'https' or 'http',
  63. new_url[0], urlquote(new_url[1]))
  64. else:
  65. newurl = urlquote(new_url[1])
  66. if request.GET:
  67. newurl += '?' + request.META['QUERY_STRING']
  68. return http.HttpResponsePermanentRedirect(newurl)
  69. def process_response(self, request, response):
  70. "Send broken link emails and calculate the Etag, if needed."
  71. if response.status_code == 404:
  72. if settings.SEND_BROKEN_LINK_EMAILS and not settings.DEBUG:
  73. # If the referrer was from an internal link or a non-search-engine site,
  74. # send a note to the managers.
  75. domain = request.get_host()
  76. referer = request.META.get('HTTP_REFERER', None)
  77. is_internal = _is_internal_request(domain, referer)
  78. path = request.get_full_path()
  79. if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer):
  80. ua = request.META.get('HTTP_USER_AGENT', '<none>')
  81. ip = request.META.get('REMOTE_ADDR', '<none>')
  82. mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain),
  83. "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \
  84. % (referer, request.get_full_path(), ua, ip),
  85. fail_silently=True)
  86. return response
  87. # Use ETags, if requested.
  88. if settings.USE_ETAGS:
  89. if response.has_header('ETag'):
  90. etag = response['ETag']
  91. else:
  92. etag = '"%s"' % md5_constructor(response.content).hexdigest()
  93. if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag:
  94. cookies = response.cookies
  95. response = http.HttpResponseNotModified()
  96. response.cookies = cookies
  97. else:
  98. response['ETag'] = etag
  99. return response
  100. def _is_ignorable_404(uri):
  101. """
  102. Returns True if a 404 at the given URL *shouldn't* notify the site managers.
  103. """
  104. for start in settings.IGNORABLE_404_STARTS:
  105. if uri.startswith(start):
  106. return True
  107. for end in settings.IGNORABLE_404_ENDS:
  108. if uri.endswith(end):
  109. return True
  110. return False
  111. def _is_internal_request(domain, referer):
  112. """
  113. Returns true if the referring URL is the same domain as the current request.
  114. """
  115. # Different subdomains are treated as different domains.
  116. return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer)
  117. def _is_valid_path(path, urlconf=None):
  118. """
  119. Returns True if the given path resolves against the default URL resolver,
  120. False otherwise.
  121. This is a convenience method to make working with "is this a match?" cases
  122. easier, avoiding unnecessarily indented try...except blocks.
  123. """
  124. try:
  125. urlresolvers.resolve(path, urlconf)
  126. return True
  127. except urlresolvers.Resolver404:
  128. return False