demand : You want to initialize some data before running the project , Including but not limited to some global variables 、 Database etc. .
Implementation method : It's simple , Just three steps
(1) Make sure app Be registered to settings In the document install_apps in :
(2) In the app Of __init__ Set... In the file default_app_config:
default_app_config = 'apps.home.apps.HomeConfig'
(3) In the app Of apps In file , Inherit AppConfig class ; rewrite name attribute , rewrite ready Method ; among name Property must match the registered app The names are the same ;ready Method to write your initialization behavior logic code .
from django.apps import AppConfig
class HomeConfig(AppConfig):
name = "apps.Home"
def ready(self):
pass
(4) perform python manage.py runserver You can see ready Method is called ;
Points of attention : Some students may find ready Method was called twice , It's because you used it python manage.py runserver This operation mode starts the project , This method will start two processes , One of the processes is used to listen for the user to modify the code and restart , But in the real world uwsgi Starting the project will only call once ready Method . If you don't want to start two processes , You can also use python manage.py runserver --noreload Start project --noreload Close the listening code and modify the meaning of restarting the program .