Domain Sniffing Middleware

My first project for the new job has been creating an internationalized version of the website. I think it also serves as a good test run for how django works with the infrastructure that's in place. Instead of having two separate django installations, each with mirrored files (save settings.LANGUAGECODE), I wrote a quick middleware which will add a session key for djangolanguage, which is used by the locale middleware to determine which version of the site to show you, based on the domain you're accessing.

I'll be the first to admit that it is a bit hackish, but I didn't want to muck about in django source like zeeg does in his example. This could definitely be abstracted a bit more in a more generic method, but deadlines are deadlines.

If you plan to use this middleware, the ordering is important. It has to be after your session middleware, but before your locale middleware. Without further ado, code!

class SniffDomainMiddleware(object):
      def process_request(self, request):
          if request.session.get('django_language', False):
              return None
              host = request.get_host()
              host_bits = host.split(':')[0].split('.')
              if 'fr' in host_bits:
                  request.session['django_language'] = 'fr'
              elif 'com' in host_bits:
                  request.session['django_language'] = 'en'
              return None