Django : Call a method only once when the django starts up

Himanshu picture Himanshu · Jan 25, 2013 · Viewed 7.8k times · Source

I want to initialize some variables (from the database) when Django starts.

I am able to get the data from the database but the problem is how should I call the initialize method . And this should be only called once.

Tried looking in other Pages, but couldn't find an answer to it.

The code currently looks something like this ::


def get_latest_dbx(request, ....):

#get the data from database


def get_latest_x(request):

get_latest_dbx(request,x,...)


def startup(request):

get_latest_x(request)

Answer

Hui Zheng picture Hui Zheng · Jan 25, 2013

Some people suggest( Execute code when Django starts ONCE only? ) call that initialization in the top-level urls.py(which looks unusual, for urls.py is supposed to handle url pattern). There is another workaround by writing a middleware: Where to put Django startup code? But I believe most of people are waiting for the ticket to be solved.

UPDATE:

Since the OP has updated the question, it seems the middleware way may be better, for he actually needs a request object in startup. All startup codes could be put in a custom middleware's process_request method, where request object is available in the first argument. After these startup codes execute, some flag may be set to avoid rerunning them later(raising MiddlewareNotUsed exception only works in __init__, which doesn't receive a request argument).

BTW, OP's requirement looks a bit weird. On one hand, he needs to initialize some variables when Django starts, on the other hand, he need request object in the initialization. But when Django starts, there may be no incoming request at all. Even if there is one, it doesn't make much sense. I guess what he actually needs may be doing some initialization for each session or user.