如何在每次Django重新启动时调用函数



我有一个Django Web服务,它在生产中使用Gunicorn托管。每次重新启动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,而是启动和停止GunicornWeb服务器

如果你想在每次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()

关于这方面的更多信息可以在Django文档中找到

最新更新