Execute Code Once upon Django Startup
When creating custom Django middleware classes, it's often necessary to execute code only once upon startup. However, using the standard approach outlined by sdolan can result in the desired code being executed twice.
Solution
To ensure code execution occurs only once, for Django versions 1.7 and above, utilize the new hook provided by Django. In your app's apps.py file:
<code class="python">from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' verbose_name = "My Application" def ready(self): pass # Your startup code here</code>
For Django versions prior to 1.7, place your startup code in any one of your INSTALLED_APPS' __init__.py files:
<code class="python">def startup(): pass # Load a big thing startup()</code>
When using ./manage.py runserver, this code will execute twice due to server validations. However, in production deployments or during automatic server reloads, the code will only execute once.
The above is the detailed content of How to Execute Code Only Once on Django Startup?. For more information, please follow other related articles on the PHP Chinese website!