如何避免AppConfig.ready()方法在Django中运行两次 [英] How to avoid AppConfig.ready() method running twice in Django

查看:468
本文介绍了如何避免AppConfig.ready()方法在Django中运行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django服务器启动时执行一些代码,但我希望它只运行一次。目前,当我启动服务器时,它会执行两次。 文档表示可能会发生这种情况,并且:

I want to execute some code at startup of Django server but I want it to run only once. Currently when I start the server it's executed twice. Documentation says that this might happen and:


您应该在AppConfig类上放置一个标志,以防止重新运行应恰好执行一次的
代码。

you should put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time.

任何想法如何实现?下面的打印语句仍然执行两次。

Any idea how to achieve this? Print statement below is still executed twice.

from django.apps import AppConfig
import app.mqtt
from apscheduler.schedulers.background import BackgroundScheduler

class MyAppConfig(AppConfig):
    name = 'app'
    verbose_name = "HomeIoT"
    run_already = False

    def ready(self):
        if MyAppConfig.run_already: return
        MyAppConfig.run_already = True
        print("Hello")


推荐答案

使用 python manage.py runserver Django启动两个进程,一个用于实际的开发服务器,另一个在代码更改时重新加载您的应用程序。

When you use python manage.py runserver Django start two processes, one for the actual development server and other to reload your application when the code change.

您还可以在不使用reload选项的情况下启动服务器,并且只会看到一个正在运行的进程只会执行一次:

You can also start the server without the reload option, and you will see only one process running will only be executed once :

python manage.py runserver --noreload

您可以看到此链接,它解析了 ready()方法在Django中运行两次

You can see this link, it resolves the ready() method running twice in Django

这篇关于如何避免AppConfig.ready()方法在Django中运行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆