我在外部网关脚本中使用Django DB模块时遇到问题。 我有下面的python文件 的的myproject /所有MyApplication / lib.py
#<path>/myproject/myapplication/lib.py
from django.db import connection
from django.db import settings
#SOME METHODS ARE HERE
使用django db模块。
我需要在同一目录 myproject / myapplication / gateway.py
下的另一个python脚本中导入 lib#<path>/myproject/myapplication/gateway.py
import sys, os
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
sys.path.append('../')
import lib
#SOME LOGIC HERE
但它失败并出现以下错误:
Fisbrok:myproject firas$ python myapplication/gateway.py
Traceback (most recent call last):
File "myapplication/gateway.py", line 7, in ?
import lib
File ".... lib.py", line 1, in ?
from django.db import connection
File "/opt/local/lib/python2.4/site-packages/django/db/__init__.py", line 14, in ?
if not settings.DATABASES:
File "/opt/local/lib/python2.4/site-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 40, in _setup
self._wrapped = Settings(settings_module)
File "/opt/local/lib/python2.4/site-packages/django/conf/__init__.py", line 75, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myproject.settings' (Is it on sys.path? Does it have syntax errors?): No module named myproject.settings
我错过了什么吗?
答案 0 :(得分:1)
你的项目目录,myproject
必须在python路径中将设置模块设置为myproject.settings
您可以通过
在gateway.py文件中设置python上的项目目录import sys
sys.path.insert(0, 'absolute/path/to/project')
行前
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"