Changes between Version 3 and Version 4 of MultiHostMiddleware


Ignore:
Timestamp:
Jan 10, 2012, 5:00:06 AM (13 years ago)
Author:
Cal Leeming
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • MultiHostMiddleware

    v3 v4  
     1
     2{{{
     3#!python
     4# File: README
     5
     6"""
     7
     8 A simple middleware component that lets you use a single Django
     9 instance to server multiple distinct hosts.
     10
     11 IMPORTANT!! Make sure this is the FIRST entry in your MIDDLEWARE_CLASSES
     12
     13 Revision log:
     14
     15 v1.2 - 10th January 2012 (Cal Leeming - cal.leeming@simplicitymedialtd.co.uk)
     16  * Added 'LoadingTime' response header (tells us how long the request took to process)
     17  * Added 'MultiHost' response header (tells us if multihost was used or not)
     18  * Added 'HOST_MIDDLEWARE_URLCONF_MAP' example
     19  * Cleaned up code slightly
     20
     21"""
     22
     23}}}
     24
     25{{{
     26#!python
     27# File: settings.py
     28
     29HOST_MIDDLEWARE_URLCONF_MAP = {
     30    # Control Panel
     31    "www.example.com": "webapp.sites.example.urls",
     32}
     33
     34}}}
    135
    236{{{
    337#!python
    438# File: multihost.py
    5 
    6 ##
    7 # A simple middleware component that lets you use a single Django
    8 # instance to server multiple distinct hosts.
    9 # 6th July 2011: IMPORTANT!! Make sure this is the FIRST entry in your MIDDLEWARE_CLASSES
    10 # - Cal
    11 ##
    1239
    1340from django.conf import settings
     
    1845    def process_request(self, request):
    1946        try:
     47            request.META["LoadingStart"] = time.time()
    2048            host = request.META["HTTP_HOST"]
    2149            if host[-3:] == ":80":
    2250                host = host[:-3] # ignore default port number, if present
    23             request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
     51            if settings.HOST_MIDDLEWARE_URLCONF_MAP.has_key(host):
     52                request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
     53                request.META["MultiHost"] = str(request.urlconf)
     54            else:
     55                request.META["MultiHost"] = str(settings.ROOT_URLCONF)
     56
    2457        except KeyError:
    2558            pass # use default urlconf (settings.ROOT_URLCONF)
    2659
    2760    def process_response(self, request, response):
     61        if request.META.has_key('MultiHost'):
     62            response['MultiHost'] = request.META.get("MultiHost")
     63
     64        if request.META.has_key('LoadingStart'):
     65            _loading_time = time.time() - int(request.META["LoadingStart"])
     66            response['LoadingTime'] = "%.2fs" % ( _loading_time, )
     67
    2868        if getattr(request, "urlconf", None):
    2969            patch_vary_headers(response, ('Host',))
Back to Top