django - settings.py seems to load multiple times?

2020-03-11 02:47发布

问题:

EDIT I miscounted - it is printed out twice, not four times.

I put this in my settings.py

print 'ola!'

and on startup "ola" is printed out twice! This seems like something is wrong with my pycharm django project ... any ideas why this would happen? It isn't in a loop or anything (that i'm aware of, anyway)

cheers!

YAY The user known only as "rohit", as per the comments, has determined that a solution can be found here: https://stackoverflow.com/a/2110584/1061426 ~ see the comment about disabling reloading.

CAUTION I don't have my Django code up and about now, so I don't know what the noload will do. Good luck, soldiers.

回答1:

If you print out the thread ID within settings.py, you will see that settings.py is actually being loaded on two different threads.

See this stackoverflow response and this article for more info.



回答2:

Actually what Django does is putting a wrapper around settings. It is basically an object (settings object if you want so) which give you access to some direct setters like settings.WHATEVER, so it appears like you access the global variables in settings.py direclty.

I really don't remember though, why the import happens twice. I looked into it once when I worked on django-dynamic-settings which uses a very similar approach as Django itself. Anyway, if you are interested in the "magic" you can follow the flow starting from the execute_from_command_line call in manage.py.



回答3:

Django does some strange things with settings.py, and it will execute more than once. I'm used to seeing it imported twice, not sure why in PyCharm you're getting four times. You have to be careful with statements with side-effects in settings.py.



回答4:

A closely-related question has been asked at least twice since. I can add that a Django core developer rejected the idea that this is any sort of Django bug; it's normal behavior.

Also see this from Graham Dumpleton.