【问题标题】:How to call a function every time Django restarts?每次Django重新启动时如何调用一个函数?
【发布时间】:2020-08-20 20:50:09
【问题描述】:

我有一个在生产环境中使用 Gunicorn 托管的 Django 网络服务。每次重新启动网络服务时,我都需要调用函数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 网络服务器

【问题讨论】:

  • 考虑到 gunicorn 可以在运行时创建和删除工作进程,您认为重启究竟是什么?

标签: python django celery gunicorn wsgi


【解决方案1】:

如果您想在 Django 每次启动时调用代码,您可以在应用配置中通过覆盖其就绪函数来执行此操作。 例如

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找到更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2019-03-13
    • 2018-01-18
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多