Add dev site switcher for testing every site from one host

With DEBUG on, ?site=<domain> selects the site without DNS or hosts
entries and is remembered in a cookie. /dev-sites/ lists all
configured sites as links.
This commit is contained in:
sajeyks 2026-09-30 14:54:38 +03:00
commit d4d3884d7c
2 changed files with 59 additions and 0 deletions

View file

@ -15,6 +15,10 @@ CACHES = {
}
}
MIDDLEWARE_CLASSES = (
'utils.middleware.DevSiteSwitcherMiddleware',
) + MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES += ("debug_toolbar.middleware.DebugToolbarMiddleware",)
INSTALLED_APPS += (

View file

@ -1,3 +1,9 @@
import json
from django.conf import settings
from django.http import HttpResponse
class MultipleProxyMiddleware(object):
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
@ -15,3 +21,52 @@ class MultipleProxyMiddleware(object):
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[-1].strip()
class DevSiteSwitcherMiddleware(object):
"""
Dev/test only (enabled from settings/local.py, i.e. DEBUG=True).
The project picks a site from the request's Host header. To test every
site from a single address without DNS or /etc/hosts entries, visit
http://<server>:8000/?site=datacenterlight.ch once; the choice is kept in
a cookie. ?site= (empty) clears it.
"""
COOKIE = 'dev_site'
def process_request(self, request):
if request.path == '/dev-sites/':
return self.sites_page()
if 'site' in request.GET:
site = request.GET['site'].strip()
else:
site = request.COOKIES.get(self.COOKIE, '')
request.META['DEV_SITE_SWITCH'] = site
if site:
request.META['HTTP_HOST'] = site
request.META.pop('HTTP_X_FORWARDED_HOST', None)
def process_response(self, request, response):
if 'site' in request.GET:
site = request.META.get('DEV_SITE_SWITCH', '')
if site:
response.set_cookie(self.COOKIE, site)
else:
response.delete_cookie(self.COOKIE)
return response
def sites_page(self):
"""A page listing every configured site as a link, on any host"""
try:
domains = sorted(
d for d in json.loads(settings.UNGLEICH_SITE_CONFIGS)
if ':' not in d)
except ValueError:
domains = []
items = ''.join(
'<li><a href="/?site={0}">{0}</a></li>'.format(d) for d in domains)
return HttpResponse(
'<!doctype html><title>Test sites</title>'
'<h1>Test sites</h1><p>Click a site to browse it; '
'<a href="/?site=">clear</a> the choice.</p><ul>{}</ul>'.format(
items))