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. csrf test by zukosdead 3 weeks, 6 days ago
  2. find even number by Rajeev529 9 months, 1 week ago
  3. Form field with fixed value by roam 10 months ago
  4. New Snippet! by Antoliny0919 10 months ago
  5. Add Toggle Switch Widget to Django Forms by OgliariNatan 1 year ago

Comments

Please login first before commenting.