Execute Code When Django Starts Once Only

Execute code when Django starts ONCE only?

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

from django.confs.urls.defaults import *
from my_app import one_time_startup

urlpatterns = ...

one_time_startup()

Where in Django can I run startup code that requires models?

The problem is that you import .models at the top of your file. This means that, when the file app.py file is loaded, Python will load the models.py file when it evalutes that line. But that is too early. You should let Django do the loading properly.

You can move the import in the def ready(self) method, such that the models.py file is imported when ready() is called by the Django framework, like:

from django.apps import AppConfig

class Pqawv1Config(AppConfig):
name = 'pqawV1'

def ready(self):
from .models import KnowledgeBase
to_load = KnowledgeBase.objects.order_by('-timestamp').first()
# Here should go the file loading code

How to execute django startup code only once

Had to modify apache httpd.conf with following lines:
WSGIDaemonProcess site-1 threads=15

WSGIProcessGroup site-1

Basicly django was running in multiple processes and threads. To make global TCP Client thread safe, lock object threading.Lock() was helpful. Also created TcpClient as singleton, just in case.

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

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.

Django 2: how to run code once on app initialization?

I think you can take advantage of the django AppConfig, docs here -> https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig

from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class YOURAPPNAMEConfig(AppConfig):
name = 'YOURAPPNAME'
verbose_name = _('VERBOSE APP NAME')

def ready(self):
CODE YOU WANT TO RUN ON APP READY

Let us know if this helps you.

Django: Run a script right after runserver

You can execute the code in the top-level urls.py. That module is imported and executed once.

urls.py

from django.confs.urls.defaults import *
from your_script import one_time_startup_function

urlpatterns = ...

one_time_startup_function()


Related Topics



Leave a reply



Submit