Save RAM with mobile middleware
A while back I wrote an article on how to set up a mobile site with Django. 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)
Related tags: django, middleware, mobile
Comments
Ludwig Pettersson http://luddep.se/
Being on a 256 slice myself, I recognize the need to utilize every single bit of ram, hehe.
Jdunck
Careful of expensive views and don’t use threading with this approach.
(Maybe settings should be thread local?)
Nathan Borror http://www.playgroundblues.com
@Jdunck - How would expensive views effect the middleware? I personally don’t use threads for anything.
Oliver Beattie http://www.obeattie.com
That’s a really nice way of handling this.
Zachary Voase http://biga.mp
You do use threads, it’s built into the Web server. Monkey patching the settings when a request comes in is very susceptible to race conditions. It would probably be better to have some sort of alternative template loader which could choose which template to load by taking a look at the request object…or something.
urban
Will it work with cache middleware? I think the cache middleware server normal page from cache if its enabled. Any fix for it?
macdet http://www.mobbing-gegner.de
thx. Now i have the hint for my faults on my site!
@Session and Authentication Middleware and before the Cache Middleware like so:
:)