| 1 | |
| 2 | {{{ |
| 3 | # File: multihost.py |
| 4 | |
| 5 | ## |
| 6 | # A simple middleware component that lets you use a single Django |
| 7 | # instance to server multiple distinct hosts. |
| 8 | ## |
| 9 | |
| 10 | from django.conf import settings |
| 11 | from django.utils.cache import patch_vary_headers |
| 12 | |
| 13 | class MultiHostMiddleware: |
| 14 | |
| 15 | def process_request(self, request): |
| 16 | try: |
| 17 | host = request.META["HTTP_HOST"] |
| 18 | if host[-3:] == ":80": |
| 19 | host = host[:-3] # ignore default port number, if present |
| 20 | request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host] |
| 21 | except KeyError: |
| 22 | pass # use default urlconf (settings.ROOT_URLCONF) |
| 23 | |
| 24 | def process_response(self, request, response): |
| 25 | if getattr(request, "urlconf", None): |
| 26 | patch_vary_headers(response, ('Host',)) |
| 27 | return response |
| 28 | }}} |