Permalink
Browse files

cache the redirects in memory to not hit the database on every request

  • Loading branch information...
1 parent 413a6e0 commit 874913662c75cfc5c4f3c31410359a5053056439 @jlecker jlecker committed Jul 2, 2012
Showing with 27 additions and 21 deletions.
  1. +27 −21 hostname_redirects/middleware.py
@@ -5,30 +5,36 @@
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):
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']
try:
- new_hostname = RedirectHost.objects.select_related('site') \
- .get(hostname=server_name).site.domain
- except RedirectHost.DoesNotExist:
+ return _get_redirect(self._cache[server_name], request)
+ except KeyError:
if getattr(settings, 'REMOVE_WWW', None) \
and server_name.startswith('www.'):
- new_hostname = server_name[4:]
- else:
- catchall = getattr(settings,
- 'CATCHALL_REDIRECT_HOSTNAME', None)
- # if catchall hostname is set, verify that the current
- # hostname is valid, and redirect if not
- if catchall and not Site.objects.filter(
- domain=server_name).exists():
- new_hostname = catchall
- else:
- # either catchall is not set or current hostname is valid
- return None
- new_location = '%s://%s%s' % (
- request.is_secure() and 'https' or 'http',
- new_hostname,
- request.get_full_path()
- )
- return HttpResponsePermanentRedirect(new_location)
+ return _get_redirect(server_name[4:], request)
+ catchall = getattr(settings,
+ 'CATCHALL_REDIRECT_HOSTNAME', None)
+ # if catchall hostname is set, verify that the current
+ # hostname is valid, and redirect if not
+ if catchall:
+ # cache all site domains in one query
+ if not hasattr(self, '_sites'):
+ self._sites = Site.objects.values_list('domain', flat=True)
+ if server_name not in self._sites:
+ return _get_redirect(catchall, request)
+ return None

0 comments on commit 8749136

Please sign in to comment.