middleware.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django.conf import settings
  2. from django import http
  3. from django.core.urlresolvers import resolve
  4. def output_function(o):
  5. return str(type(o))
  6. class SetRemoteAddrMiddleware(object):
  7. def process_request(self, request):
  8. if not request.META.has_key('REMOTE_ADDR'):
  9. try:
  10. request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR']
  11. except:
  12. request.META['REMOTE_ADDR'] = '1.1.1.1' # This will place a valid IP in REMOTE_ADDR but this shouldn't happen
  13. class SmartAppendSlashMiddleware(object):
  14. """
  15. "SmartAppendSlash" middleware for taking care of URL rewriting.
  16. This middleware appends a missing slash, if:
  17. * the SMART_APPEND_SLASH setting is True
  18. * the URL without the slash does not exist
  19. * the URL with an appended slash does exist.
  20. Otherwise it won't touch the URL.
  21. """
  22. def process_request(self, request):
  23. """
  24. Rewrite the URL based on settings.SMART_APPEND_SLASH
  25. """
  26. # Check for a redirect based on settings.SMART_APPEND_SLASH
  27. host = http.get_host(request)
  28. old_url = [host, request.path]
  29. new_url = old_url[:]
  30. # Append a slash if SMART_APPEND_SLASH is set and the resulting URL
  31. # resolves.
  32. if settings.SMART_APPEND_SLASH and (not old_url[1].endswith('/')) and not _resolves(old_url[1]) and _resolves(old_url[1] + '/'):
  33. new_url[1] = new_url[1] + '/'
  34. if settings.DEBUG and request.method == 'POST':
  35. raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have SMART_APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set SMART_APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1])
  36. if new_url != old_url:
  37. # Redirect
  38. if new_url[0]:
  39. newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1])
  40. else:
  41. newurl = new_url[1]
  42. if request.GET:
  43. newurl += '?' + request.GET.urlencode()
  44. return http.HttpResponsePermanentRedirect(newurl)
  45. return None
  46. def _resolves(url):
  47. try:
  48. resolve(url)
  49. return True
  50. except http.Http404:
  51. return False