Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call django.setup() in console_script?

The current django docs tell me this:

django.setup() may only be called once.

Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you can’t avoid that, put the call to django.setup() inside an if block:

if __name__ == '__main__':
    import django
    django.setup()

Source: Calling django.setup() is required for “standalone” Django usage

I am using entry points in setup.py. This way I don't have __name__ == '__main__'.

Question

How to ensure django.setup() gets only called once if you use console_scripts?

Where should I put django.setup()?

Background

The actual error I have: Django hangs. Here is the reason: https://code.djangoproject.com/ticket/27176

I want to port my application to the current django version. Changing to a management command is not an option, since other (third party applications) rely on the existence of my console scripts.

like image 356
guettli Avatar asked Sep 26 '16 13:09

guettli


People also ask

What does Django setup () do?

It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation.

How do I access Django settings?

When you use Django, you have to tell it which settings you're using. Do this by using an environment variable, DJANGO_SETTINGS_MODULE . The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite. settings .


1 Answers

Here https://docs.djangoproject.com/en/1.10/_modules/django/#setup we can see what django.setup actually does.

Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if set_prefix is True.

So basically to ensure that setup was already done we can check if apps are ready and settings are configured

from django.apps import apps
from django.conf import settings

if not apps.ready and not settings.configured:
    django.setup()
like image 58
Sardorbek Imomaliev Avatar answered Sep 18 '22 03:09

Sardorbek Imomaliev