开发者

Initializing Custom Objects in Django Settings

I am new to Django and Python.

I have created a python file in my application root called services.py. Inside this file开发者_开发技巧 I have a class named SchedulerService. I am trying to initialize an instance of SchedulerService in the settings module so it will be available every time a view is executed. In the Java world I would use a singleton object and initialize it with an auto init servlet or a MBean.

The problem I am running into is that I cannot import any custom modules into the settings.py file. For instance:

settings.py

from theapp.services import SchedulerService

I get the following message when I attempt to start my development server

Error: Can't find the file 'settings.py' in the directory containing 'manage.py'. It appears you've customized things.
You'll have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it's causing an ImportError somehow.)

I get the same error if I try to import a view or model class into the settings module.

Perhaps I am going about it entirely wrong and should be implementing this in another manner.

Any help will be appreciated.


That particular message is characteristic of a circular import issue - theapp.services probably imports settings, or imports something which in turn imports settings, and Python can't resolve the dependency.

You could probably resolve this by moving one of the imports into a function or method, but I should say that settings.py is emphatically not the place to be instantiating things. It really, really isn't meant for that.

I hope that due to your reference to a "global" object, you've already considered thread-safety issues: dont' forget, Django processes are not created and destroyed for each request, one process can serve multiple requests before being destroyed, so any global objects will be shared between those requests. If that's not what you want, you'll need to instantiate the object within the request cycle itself, perhaps in middleware, and associate it with an object that only lasts the lifetime of the request - in other words, probably the request object itself.

Otherwise, you could do something similar to the admin application, and put your instantiation call in urls.py.


Does your "theapp" directory contain an __init__.py file? It's necessary to get recognized as a python module.


You can use a module level "global" variable in the same views.py

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜