Skip to content

Commit

Permalink
cache the redirects in memory to not hit the database on every request
Browse files Browse the repository at this point in the history
  • Loading branch information
jlecker committed Jul 2, 2012
1 parent 413a6e0 commit 8749136
Showing 1 changed file with 27 additions and 21 deletions.
48 changes: 27 additions & 21 deletions hostname_redirects/middleware.py
Expand Up @@ -5,30 +5,36 @@
from hostname_redirects.models import RedirectHost from hostname_redirects.models import RedirectHost




def _get_redirect(new_hostname, request):
new_location = '%s://%s%s' % (
request.is_secure() and 'https' or 'http',
new_hostname,
request.get_full_path()
)
return HttpResponsePermanentRedirect(new_location)


class HostnameRedirectMiddleware(object): class HostnameRedirectMiddleware(object):
def process_request(self, request): def process_request(self, request):
# cache all redirect hostnames in one query
if not hasattr(self, '_cache'):
self._cache = dict(
RedirectHost.objects.values_list('hostname', 'site__domain'))
server_name = request.META['SERVER_NAME'] server_name = request.META['SERVER_NAME']
try: try:
new_hostname = RedirectHost.objects.select_related('site') \ return _get_redirect(self._cache[server_name], request)
.get(hostname=server_name).site.domain except KeyError:
except RedirectHost.DoesNotExist:
if getattr(settings, 'REMOVE_WWW', None) \ if getattr(settings, 'REMOVE_WWW', None) \
and server_name.startswith('www.'): and server_name.startswith('www.'):
new_hostname = server_name[4:] return _get_redirect(server_name[4:], request)
else: catchall = getattr(settings,
catchall = getattr(settings, 'CATCHALL_REDIRECT_HOSTNAME', None)
'CATCHALL_REDIRECT_HOSTNAME', None) # if catchall hostname is set, verify that the current
# if catchall hostname is set, verify that the current # hostname is valid, and redirect if not
# hostname is valid, and redirect if not if catchall:
if catchall and not Site.objects.filter( # cache all site domains in one query
domain=server_name).exists(): if not hasattr(self, '_sites'):
new_hostname = catchall self._sites = Site.objects.values_list('domain', flat=True)
else: if server_name not in self._sites:
# either catchall is not set or current hostname is valid return _get_redirect(catchall, request)
return None return None
new_location = '%s://%s%s' % (
request.is_secure() and 'https' or 'http',
new_hostname,
request.get_full_path()
)
return HttpResponsePermanentRedirect(new_location)

0 comments on commit 8749136

Please sign in to comment.