PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/servicios_web/gae/django-guestbook/src/django/middleware/common.py

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