I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan here, but the "Hello" message is output to the terminal twice. E.g.
from django.core.exceptions import MiddlewareNotUsed from django.conf import settings class StartupMiddleware(object): def __init__(self): print "Hello world" raise MiddlewareNotUsed('Startup complete')
and in my Django settings file, I've got the class included in the
But when I run Django using runserver and request a page, I get in the terminal
Django version 1.3, using settings 'config.server' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Hello world [22/Jul/2011 15:54:36] "GET / HTTP/1.1" 200 698 Hello world [22/Jul/2011 15:54:36] "GET /static/css/base.css HTTP/1.1" 200 0
Any ideas why "Hello world" is printed twice? Thanks.
Update from Pykler's answer below: Django 1.7 now has a hook for this
Don't do it this way.
You don't want "middleware" for a one-time startup thing.
You want to execute code in the top-level
urls.py. That module is imported and executed once.
from django.confs.urls.defaults import * from my_app import one_time_startup urlpatterns = ... one_time_startup()
from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' verbose_name = "My Application" def ready(self): pass # startup code here
default_app_config = 'myapp.apps.MyAppConfig'
The number one answer does not seem to work anymore, urls.py is loaded upon first request.
What has worked lately is to put the startup code in any one of your INSTALLED_APPS init.py e.g.
def startup(): pass # load a big thing startup()
./manage.py runserver ... this gets executed twice, but that is because runserver has some tricks to validate the models first etc ... normal deployments or even when runserver auto reloads, this is only executed once.