Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Adding middleware to do all the no-www stuff.

  • Loading branch information...
commit 18778885ce8491e7ecc16b58f23d481c42c5131c 1 parent 0658f7d
Bryan Veloso bryanveloso authored
115 applications/core/middleware/__init__.py
... ... @@ -0,0 +1,115 @@
  1 +"""
  2 +URL Middleware
  3 +Stefano J. Attardi (attardi.org)
  4 +
  5 +$Id: url.py 203 2007-03-06 17:04:55Z asolovyov $
  6 +$URL$
  7 +
  8 +Cleans up urls by adding/removing trailing slashes, adding/removing
  9 +the www. prefix, and allowing the language to be set from the url.
  10 +
  11 +If APPEND_SLASH is set to False, trailing slashes are removed from the
  12 +urls, except for urls which have an explicit trailing slash in
  13 +urls.py, in which case a trailing slash is added.
  14 +
  15 +If REMOVE_WWW is set to True, the www. prefix is removed.
  16 +
  17 +Finally, ?lang=xx can be appended to any url to override the default
  18 +language setting. This override is remembered for the following
  19 +requests. For example, /article?lang=it would show the article in
  20 +Italian regardless of brower settings or cookies, and any following
  21 +request to the site would be shown in Italian by default.
  22 +
  23 +Changelog
  24 +
  25 +1.3
  26 +Only use sessions for the language preference if the session
  27 +cookie has already been set (regardless of whether session middleware
  28 +is active). Otherwise use the plain django_language cookie.
  29 +Only import the FlatPages module if it is active.
  30 +
  31 +1.2
  32 +Added support for FlatPages.
  33 +Switched to Django's resolve function (with workaround for when it
  34 +returns None).
  35 +
  36 +1.1
  37 +Various bugfixes.
  38 +
  39 +1.0
  40 +First release.
  41 +"""
  42 +__version__ = "1.3"
  43 +__license__ = "Python"
  44 +__copyright__ = "Copyright (C) 2006, Stefano J. Attardi"
  45 +__author__ = "Stefano J. Attardi <http://attardi.org/>"
  46 +__contributors__ = ["Antonio Cavedoni <http://cavedoni.com/>"]
  47 +
  48 +from django.conf import settings
  49 +from django.http import HttpResponseRedirect, Http404
  50 +from django.core.urlresolvers import resolve
  51 +from django.utils.translation import check_for_language
  52 +import os
  53 +
  54 +class UrlMiddleware:
  55 +
  56 + def process_request(self, request):
  57 +
  58 + # Change the language setting for the current page
  59 + if "lang" in request.GET and check_for_language(request.GET["lang"]):
  60 + if hasattr(request, 'session'):
  61 + request.session['django_language'] = request.GET["lang"]
  62 + else:
  63 + request.COOKIES['django_language'] = request.GET["lang"]
  64 +
  65 + # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW
  66 + httpHost = request.META.get('HTTP_HOST', '')
  67 + old_url = [httpHost, request.path]
  68 + new_url = old_url[:]
  69 +
  70 + # if REMOVE_WWW is True, remove the www. from the urls if necessary
  71 + if hasattr(settings, "REMOVE_WWW") and settings.REMOVE_WWW and old_url[0].startswith('www.'):
  72 + new_url[0] = old_url[0][4:]
  73 +
  74 + if hasattr(settings, "APPEND_SLASH") and not settings.APPEND_SLASH:
  75 + # if the url is not found, try with(out) the trailing slash
  76 + if not self._urlExists(old_url[1]):
  77 +
  78 + if old_url[1][-1] == "/":
  79 + other = old_url[1][:-1]
  80 + else:
  81 + other = old_url[1] + "/"
  82 +
  83 + if self._urlExists(other):
  84 + new_url[1] = other
  85 +
  86 + if new_url != old_url:
  87 + # Redirect
  88 + newurl = "%s://%s%s" % (os.environ.get('HTTPS') == 'on' and 'https' or 'http', new_url[0], new_url[1])
  89 + if request.GET:
  90 + newurl += '?' + request.GET.urlencode()
  91 + return HttpResponseRedirect(newurl)
  92 +
  93 + return None
  94 +
  95 + def process_response(self, request, response):
  96 +
  97 + # Change the language setting for future pages
  98 + if "lang" in request.GET and check_for_language(request.GET["lang"]):
  99 + if 'sessionid' in request.COOKIES:
  100 + request.session['django_language'] = request.GET["lang"]
  101 + else:
  102 + response.set_cookie('django_language', request.GET["lang"])
  103 +
  104 + return response
  105 +
  106 + def _urlExists(self, path):
  107 + try:
  108 + if resolve(path) is None: raise Http404 # None?!? You mean 404...
  109 + return True
  110 + except Http404:
  111 + # check for flatpages
  112 + if "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware" in settings.MIDDLEWARE_CLASSES:
  113 + from django.contrib.flatpages.models import FlatPage
  114 + return FlatPage.objects.filter(url=path, sites__id=settings.SITE_ID).count() == 1
  115 +
0  applications/__init__.py → applications/core/middleware/url.py
File renamed without changes
2  settings.py
@@ -31,6 +31,7 @@
31 31 'django.middleware.common.CommonMiddleware',
32 32 'django.middleware.http.SetRemoteAddrFromForwardedFor',
33 33 'django.contrib.sessions.middleware.SessionMiddleware',
  34 + 'applications.core.middleware.url.UrlMiddleware', # Custom Middleware
34 35 'django.contrib.auth.middleware.AuthenticationMiddleware',
35 36 'django.middleware.doc.XViewMiddleware',
36 37 'django.middleware.http.ConditionalGetMiddleware',
@@ -38,6 +39,7 @@
38 39 )
39 40 USE_ETAGS = True
40 41 APPEND_SLASH = True
  42 +REMOVE_WWW = True
41 43
42 44
43 45 # Template Settings

0 comments on commit 1877888

Please sign in to comment.
Something went wrong with that request. Please try again.