Skip to content
Advertisement

Execute code when Django starts ONCE only?

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.

JavaScript

and in my Django settings file, I’ve got the class included in the MIDDLEWARE_CLASSES list.

But when I run Django using runserver and request a page, I get in the terminal

JavaScript

Any ideas why “Hello world” is printed twice? Thanks.

Advertisement

Answer

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.

urls.py

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement