Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid AppConfig.ready() method running twice in Django

Tags:

python

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") 
like image 386
Koooop Avatar asked Nov 19 '15 21:11

Koooop


2 Answers

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

like image 117
RedBencity Avatar answered Sep 20 '22 23:09

RedBencity


if you don't want to use --noreload you can:

replace the line in your app's __init__.py that you use to specify the config:

default_app_config = 'mydjangoapp.apps.MydjangoappConfig' 

by this:

import os  if os.environ.get('RUN_MAIN', None) != 'true':     default_app_config = 'mydjangoapp.apps.MydjangoappConfig' 
like image 31
Mohamed Benkedadra Avatar answered Sep 21 '22 23:09

Mohamed Benkedadra