Subdomain Middleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class SubdomainMiddleware:
    """ Make the subdomain publicly available to classes """
    
    def process_request(self, request):
        domain_parts = request.get_host().split('.')
        if (len(domain_parts) > 2):
            subdomain = domain_parts[0]
            if (subdomain.lower() == 'www'):
                subdomain = ''
            domain = '.'.join(domain_parts[1:])
        else:
            subdomain = ''
            domain = request.META['HTTP_HOST']
        
        request.subdomain = subdomain
        request.domain = domain

Comments

claudep (on March 18, 2009):

This is useful, thanks.

However, it might be safer to use the request get_host() method instead of META['HTTP_HOST'], because it is not guaranteed to be set. E.g. in tests, META['HTTP_HOST'] is not defined.

#

xhenxhe (on April 3, 2009):

Thanks. I've updated the snippet.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.