开发者

Django app initalization code (like connecting to signals)

开发者 https://www.devze.com 2022-12-17 23:19 出处:网络
I need a place to run an initialization code that is application specific (like connecting to signals).

I need a place to run an initialization code that is application specific (like connecting to signals). When I put the code to __init__.py module of an application I've ended up with a circular import of the models.

Is there a way to fire a function when the framework is setup and before any request is executed?

I use quite old version of django 96.6, but I'm also interested in the solutions for the current version.

Regarding the duplication of other questions: Here is how the question differ from the duplicates suggested by S.Lott in comments:

  • Correct place to put extra startup code in django? Django need to be fully initialized when the function is ran. So code in manage.py won't work.

  • Where should I place the one-time operation operation in the Django framework? The function initialize the connection between my applications. So the code must be ran in each thread that will actually handle the requests.

Comments to current solutions: I can't use urls as most of my apps don't ha开发者_开发技巧ve any urls exposed. They just listen to signals and store additional information in the database.


Signals, specifically, are recommended to be put in the models.py of your app.

Try models.py or urls.py and let us know if you have any luck.


The best place for stuff like this... anywhere, just import it in your urls.py file (for obvious reasons urls are loading before any requests).


If you don't provide urls, then you really need to put it in models.py, that's just the way it is.

Now, on to your problems: You want to define it in its own module, great, do that. To avoid a circular import, use django.db.models.get_model to return the model dynamically for you. You can provide an initialisation function for your signals module to import the relevant model and connect the relevant signals. This function would then be called at the end of models.py, being run only ever once and after your model is initialised.

There's still a chance that this wont work (if the models aren't yet ready when you set it up), but give it a try and let us know.


For me, the following works:

In init.py:

from . import models
from . import signals

signals.py imports from models, but not vice versa. signals.py contains module code that is run immediately when it is imported and is thus run when the django server starts.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号