Django 每次重启时如何调用一个函数?
How to call a function every time Django restarts?
我有一个在生产环境中使用 Gunicorn 托管的 Django 网络服务。每次重新启动 web 服务时,我都需要调用函数 restart_event
。这是函数的伪代码
def restart_event():
"""This function should be called everytime Django restarts"""
# read list of registered companies from the database
companies = Company.objects.all()
for company in companies:
# perform various operations on the data
business_logic1(company)
business_logic2(company)
change_celery_settings()
如何配置Django使得每次Django重启时调用上述函数?请注意,由于正在使用 Gunicorn,因此我不会执行 python manage.py runserver
而我将启动和停止 Gunicorn 网络服务器
如果您想在每次 Django 启动时调用代码,您可以在应用程序配置中覆盖它的 ready 函数来实现。
例如
class FooConfig(AppConfig):
def ready(self):
# read list of registered companies from the database
companies = Company.objects.all()
for company in companies:
# perform various operations on the data
business_logic1(company)
business_logic2(company)
change_celery_settings()
可以找到关于此的更多信息over in the Django docs
我有一个在生产环境中使用 Gunicorn 托管的 Django 网络服务。每次重新启动 web 服务时,我都需要调用函数 restart_event
。这是函数的伪代码
def restart_event():
"""This function should be called everytime Django restarts"""
# read list of registered companies from the database
companies = Company.objects.all()
for company in companies:
# perform various operations on the data
business_logic1(company)
business_logic2(company)
change_celery_settings()
如何配置Django使得每次Django重启时调用上述函数?请注意,由于正在使用 Gunicorn,因此我不会执行 python manage.py runserver
而我将启动和停止 Gunicorn 网络服务器
如果您想在每次 Django 启动时调用代码,您可以在应用程序配置中覆盖它的 ready 函数来实现。 例如
class FooConfig(AppConfig):
def ready(self):
# read list of registered companies from the database
companies = Company.objects.all()
for company in companies:
# perform various operations on the data
business_logic1(company)
business_logic2(company)
change_celery_settings()
可以找到关于此的更多信息over in the Django docs