Created
September 1, 2015 04:28
-
-
Save mascot6699/05b0c07d72b3db93ed6a to your computer and use it in GitHub Desktop.
Django MultiHostMiddleware: A simple middleware component that lets you use a single Django instance to server multiple distinct hosts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# File: multihost.py | |
import time | |
from django.conf import settings | |
from django.utils.cache import patch_vary_headers | |
class MultiHostMiddleware: | |
def process_request(self, request): | |
try: | |
request.META["LoadingStart"] = time.time() | |
host = request.META["HTTP_HOST"] | |
#if host[-3:] == ":80": | |
# host = host[:-3] # ignore default port number, if present | |
# best way to do this. | |
host_port = host.split(':') | |
if len(host_port)==2: | |
host = host_port[0] | |
if settings.HOST_MIDDLEWARE_URLCONF_MAP.has_key(host): | |
request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host] | |
request.META["MultiHost"] = str(request.urlconf) | |
else: | |
request.META["MultiHost"] = str(settings.ROOT_URLCONF) | |
except KeyError: | |
pass # use default urlconf (settings.ROOT_URLCONF) | |
def process_response(self, request, response): | |
if request.META.has_key('MultiHost'): | |
response['MultiHost'] = request.META.get("MultiHost") | |
if request.META.has_key('LoadingStart'): | |
_loading_time = time.time() - int(request.META["LoadingStart"]) | |
response['LoadingTime'] = "%.2fs" % ( _loading_time, ) | |
if getattr(request, "urlconf", None): | |
patch_vary_headers(response, ('Host',)) | |
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# File: README | |
""" | |
IMPORTANT!! Make sure this is the FIRST entry in your MIDDLEWARE_CLASSES | |
""" | |
HOST_MIDDLEWARE_URLCONF_MAP = { | |
# Control Panel | |
"www.example.com": "webapp.sites.example.urls", | |
"test.mascot6699.com": "webapp.sites.mascot6699.urls", | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment