Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 830
Himanshu Avatar asked Jan 25 '13 06:01

Himanshu


2 Answers

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.

like image 164
Hui Zheng Avatar answered Oct 21 '22 23:10

Hui Zheng


there are some cheats for this. The general solution is trying to include the initial code in some special places, so that when the server starts up, it will run those files and also run the code.

Have you ever tried to put print 'haha' in the settings.py files :) ?

Note: be aware that settings.py runs twice during start-up

like image 38
Thai Tran Avatar answered Oct 21 '22 23:10

Thai Tran