程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to perform a wave of initialization to add data when a Django application starts? Just three simple steps

編輯:Python

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved