我为myapp
应用程序创建了一个数据库ruter
在档案/myproject/myapp/routers.py
class ShardingRouter(object):
def db_for_read(self, model, **hints):
return 'default'
def db_for_write(self, model, **hints):
return 'default'
def allow_relation(self, obj1, obj2, **hints):
return None
def allow_syncdb(self, db, model):
return None
在settings.py
我有:
from django.db import connections
DATABASE_ROUTERS = ['myproject.myapp.routers.ShardingRouter',]
这适用于通过wsgi运行的普通应用程序,但我有一个CLI脚本/myproject/parser_jobs.py
它从cron开始或从CLI手动:
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
...
...
if __name__ == "__main__":
do_some_long_boring_work()
现在,当我运行此脚本时,我收到导入错误:
Traceback (most recent call last):
File "/hosting/myproject/myproject/parser_jobs.py", line 20, in <module>
import settings
File "/hosting/myproject/myproject/settings.py", line 46, in <module>
from django.db import connections
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 95, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myproject.myproject' (Is it on sys.path?): cannot import name connections
看起来它找到了settings.py,但导入它时from django.db import connections
失败了。如果我评论这个字符串,它可以工作,但没有我的数据库路由器:(我可以在任何地方添加using()
,但它并不酷。
因此,网站运行良好,但cli脚本失败。请帮助!
更新:/hosting/myproject/myproject/parser_jobs.py
在添加数据库路由器之前从cli工作得很好
pprint
的 sys.path
:
['/hosting/myproject/myproject',
'/hosting/myproject',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/pymodules/python2.7']
更新:wsgi脚本,网站运行良好:
import os
import sys
path = '/hosting/myproject'
if path not in sys.path:
sys.path.insert(0, path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
答案 0 :(得分:1)
我的脚本与settings.py
在同一个文件夹中
当我将它从/hosting/myproject/myproject/parser_jobs.py
移到/hosting/myproject/parser_jobs.py
(django1.4 manage.py应该在哪里)时,它变得正常工作。
我还将os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
更改为os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
现在它有效!
在以前的位置parser_jobs.py
仅在没有数据库路由器的情况下工作