Save RAM with mobile middleware
7 October 2008 — A while back I wrote an article on how to set up a mobile site with Django ../going-mobile. Currently I have a Slicehost account which includes 256MB of RAM. My resources are tight and I really dislike having another set of unnecessary Apache processes for a mobile site that, aside from different templates, is using the same code base. The solution is quite simple, write a middleware.
The following code checks the incoming request for ’m’ or ‘mobile’ in the domain name. If it exists the TEMPLATE_DIRS is replaced by a MOBILE_TEMPLATE_DIRS setting:
class MobileMiddleware(object): def process_request(self, request): domain = request.META.get('HTTP_HOST', '').split('.') if 'm' in domain or 'mobile' in domain: settings.TEMPLATE_DIRS = settings.MOBILE_TEMPLATE_DIRS else: settings.TEMPLATE_DIRS = settings.DESKTOP_TEMPLATE_DIRS
You’ll notice this requires you to also have a DESKTOP_TEMPLATE_DIRS (or whatever you want to call it) so you can switch back to the desktop version.
If you’re using any sort of caching you’ll want be sure and change CACHE_MIDDLEWARE_KEY_PREFIX when you change to mobile templates and back again.
You’ll probably want to place this middleware after Session and Authentication Middleware and before the Cache Middleware like so:
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'playgroundblues.middleware.MobileMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', )
Go Green! Save RAM! (kidding)