middleware.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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[
  13. "REMOTE_ADDR"
  14. ] = "1.1.1.1" # This will place a valid IP in REMOTE_ADDR but this shouldn't happen
  15. class SmartAppendSlashMiddleware(object):
  16. """
  17. "SmartAppendSlash" middleware for taking care of URL rewriting.
  18. This middleware appends a missing slash, if:
  19. * the SMART_APPEND_SLASH setting is True
  20. * the URL without the slash does not exist
  21. * the URL with an appended slash does exist.
  22. Otherwise it won't touch the URL.
  23. """
  24. def process_request(self, request):
  25. """
  26. Rewrite the URL based on settings.SMART_APPEND_SLASH
  27. """
  28. # Check for a redirect based on settings.SMART_APPEND_SLASH
  29. host = http.get_host(request)
  30. old_url = [host, request.path]
  31. new_url = old_url[:]
  32. # Append a slash if SMART_APPEND_SLASH is set and the resulting URL
  33. # resolves.
  34. if (
  35. settings.SMART_APPEND_SLASH
  36. and (not old_url[1].endswith("/"))
  37. and not _resolves(old_url[1])
  38. and _resolves(old_url[1] + "/")
  39. ):
  40. new_url[1] = new_url[1] + "/"
  41. if settings.DEBUG and request.method == "POST":
  42. 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." % (
  43. new_url[0],
  44. new_url[1],
  45. )
  46. if new_url != old_url:
  47. # Redirect
  48. if new_url[0]:
  49. newurl = "%s://%s%s" % (
  50. request.is_secure() and "https" or "http",
  51. new_url[0],
  52. new_url[1],
  53. )
  54. else:
  55. newurl = new_url[1]
  56. if request.GET:
  57. newurl += "?" + request.GET.urlencode()
  58. return http.HttpResponsePermanentRedirect(newurl)
  59. return None
  60. def _resolves(url):
  61. try:
  62. resolve(url)
  63. return True
  64. except http.Http404:
  65. return False