Login

Serve multiple hostnames with different URLCONF's from one Django instance

Author:
rmt
Posted:
May 17, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

This works with Django 1.0.0 and later. It sets the request.urlconf variable to an alternate urlconf, if there's a match to the hostname in settings.MULTIHOST_URLCONF_MAP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File: django_multihost.py
#
# A simple middleware component that lets you use a single Django
# instance to server multiple distinct hosts.
#
# Example usage (in settings.py):
#   MIDDLEWARE_CLASSES = (
#      ...,
#      'django_multihost.MultiHostMiddleware',
#   )
#   MULTIHOST_URLCONF_MAP = {
#     'domain1.com'     : 'app1.urls',
#     'domain1.com:8080': 'app1.urls',
#     'domain2.com'     : 'app2.urls',
#   }
#
# If a host wasn't found, settings.ROOT_URLCONF will be used.
#

from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.core.exceptions import MiddlewareNotUsed

class MultiHostMiddleware:
    def __init__(self):
        if not hasattr(settings, 'MULTIHOST_URLCONF_MAP'):
            raise MiddlewareNotUsed

    def process_request(self, request):
        try:
            host = request.META["HTTP_HOST"]
            if host[-3:] == ":80":
                host = host[:-3] # ignore default port number, if present
            request.urlconf = settings.MULTIHOST_URLCONF_MAP[host]
        except KeyError:
            pass # use default urlconf (settings.ROOT_URLCONF)

    def process_response(self, request, response):
        if getattr(request, "urlconf", None):
            patch_vary_headers(response, ('Host',))
        return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.