Home > Article > Backend Development > How to Execute Code Once on Django Startup with AppConfig?
Execute Code Once on Django Startup with AppConfig
When building Django applications, there may be instances where you want to run specific code only once at startup. A Django middleware class can be utilized to achieve this, but in earlier versions, it could result in the code being executed more than once.
Solution for Django Versions < 1.7
For Django versions prior to 1.7, it was recommended to place the startup code in one of the INSTALLED_APPS' __init__.py files. Here's an example:
<code class="python">def startup(): pass # load a big thing startup()</code>
Solution for Django 1.7 and Above
Django 1.7 introduced the AppConfig.ready() method, which allows you to specify startup code. Using this method ensures that the code runs only once during app loading.
<code class="python"># myapp/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' verbose_name = "My Application" def ready(self): pass # startup code here</code>
Additional Notes
When using ./manage.py runserver, the startup code may execute twice due to internal server operations. However, in typical deployment scenarios or automated reloads, the code is executed only once.
The above is the detailed content of How to Execute Code Once on Django Startup with AppConfig?. For more information, please follow other related articles on the PHP Chinese website!