Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

python - How to avoid AppConfig.ready() method running twice in 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:

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...