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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…