Problem:
When implementing a Django middleware class intended to execute only once at startup to initialize additional code, the message "Hello world" is printed twice.
Solution:
For Django >= 1.7:
Use the ready() method in an AppConfig class:
<code class="python"># myapp/apps.py class MyAppConfig(AppConfig): name = 'myapp' verbose_name = "My Application" def ready(self): # startup code goes here</code>
For Django < 1.7:
Place the startup code in the __init__.py file of any installed app:
<code class="python"># myapp/__init__.py def startup(): # startup code goes here startup()
Explanation:
Using the ready() method in Django >= 1.7 ensures that the code is executed after Django has finished loading all models and migrations. For Django < 1.7, placing the code in the __init__.py ensures that it runs upon import, which occurs once per process.
The above is the detailed content of How to Execute Code Only Once at Django Startup?. For more information, please follow other related articles on the PHP Chinese website!