from django.conf import settings from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect import django.core.exceptions import logging import re import os # Check for the existance of a lockfile. If the lockfile doesn't exist, deny access to everywhere except settings.FIRSTRUN_APP_ROOT # If the lockfile exists, throw django.core.exceptions.MiddlewareNotUsed() so that this class is unloaded class FirstRunMiddleware: def __init__(self): if not self.is_first_run(): logging.debug('FirstRunMiddleware: FirstRun not required, unloading for process lifetime.') raise django.core.exceptions.MiddlewareNotUsed() self.p = re.compile(''.join(['^', settings.FIRSTRUN_APP_ROOT])) def process_request(self, request): if self.p.match(request.path) == None: if self.is_first_run(): logging.debug(''.join(['FirstRunMiddleware: Denying access to ', request.path, ' FirstRun needed.'])); return redirect(settings.FIRSTRUN_APP_ROOT) else: # Will only be executed between the time firstrun has been completed, until the process is regenerated (typically on the scale of mins). logging.debug('FirstRunMiddleware: FirstRun completed, resuming normal flow.') def is_first_run(self): return not os.path.exists(''.join([settings.PROJECT_PATH, settings.FIRSTRUN_LOCKFILE]))