Off late there was a requirement by one of the publication’s PO on there Django app. The requirement was to have a maintenance mode/panic mode feature, which when enabled during rollouts to production or if there are some issues with production code will show a nice page with information saying “The website is under maintenance”.
It took me by surprise as I never though of implementing it on Django apps before. I have seen this feature in our Java Spring/Escenic CMS. I have also seen the same feature in Drupal, WordPress too. I was excited to implement the same with Django.
Below mentioned is the code for my middleware.py
import logging from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from mymodel.models import SiteConfiguration log = logging.getLogger(__name__) class MaintenanceModeMiddleWare(object): def process_request(self, request): log.info('coming inside maintenance mode middleware') if request.path.startswith(reverse('admin:index')) or request.path.startswith(reverse('contactus')): return None try: config = SiteConfiguration.objects.all() if config.panic_mode: return render(request, 'core/maintenance.html') except Exception as exception: print exception.message log.error("exception while fetching panic mode data, might be the panic mode index is not found : %s " % exception.message) return None
The middleware created above will intercept each request and SiteConfiguration model will tell if the panic mode is set or not. If the panic mode is set then the request renders a maintenance.html page. The middleware also makes exception to some requests, the one going to admin page ( as the panic mode is enabled/disabled there) and to contactus page.
Now, the model SiteConfiguration is quite simple :
from django.db import models class SiteConfiguration(models.Model): panic_mode = models.BooleanField(default=False) def __unicode__(self): return 'Panic Mode' class Meta: verbose_name_plural = 'Site Configuration'
It might not be the cleanest solution but it does the job pretty well.