将模型拆分为多个文件 Python 导入包/子包
我遇到了以下错误:
Error: ImportError: No module named models.account
我正在尝试将我的模型拆分开。
这是我的项目结构:
site
| site
| | models
| | | __init__.py
| | | account.py
| | views
| | __init__.py
| | site.py
| __init__.py
| resources.py
| routes.py
| security.py
site/site/views/site.py
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from site.models.account import User
@view_config(context='pyramid.httpexceptions.HTTPForbidden',
renderer='generic/login.mako')
@view_config(route_name='generic_login', renderer='generic/login.mako')
def login(request):
if request.scheme == 'http':
request.scheme = 'https'
#return HTTPFound(location=request.url)
if 'form.submitted' in request.params:
uemail = request.params['email']
pw = request.params['pass']
user = User.objects(email=uemail).first()
return {}
路径
/Volumes/workspace/py/website/site/bin
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/WebError-0.10.3-py2.7.egg
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/Pygments-1.6-py2.7.egg
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/Tempita-0.5.1-py2.7.egg
/Volumes/workspace/py/website/site/site
/Volumes/workspace/py/website/site/lib/python2.7/site-packages/WebHelpers-1.3-py2.7.egg
/Volumes/workspace/py/website/site/lib/python27.zip
/Volumes/workspace/py/website/site/lib/python2.7
/Volumes/workspace/py/website/site/lib/python2.7/plat-darwin
/Volumes/workspace/py/website/site/lib/python2.7/plat-mac
/Volumes/workspace/py/website/site/lib/python2.7/plat-mac/lib-scriptpackages
/Volumes/workspace/py/website/site/lib/python2.7/lib-tk
/Volumes/workspace/py/website/site/lib/python2.7/lib-old
/Volumes/workspace/py/website/site/lib/python2.7/lib-dynload
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/Volumes/workspace/py/website/site/lib/python2.7/site-packages
我刚开始学习Python,所以在努力弄明白这个问题。
1 个回答
0
from site.views import blah
site
是一个标准的 Python 模块的名字,具体可以查看官方文档。这个模块有点特殊,它在解释器启动时会自动加载。这可能会导致问题,特别是如果系统的 site
模块覆盖了你自己写的模块。
你可以尝试用一些方法来解决这个问题,比如
from ..models.account import User
但最终,给你的项目换个名字可能会更好。
另一个常见的问题是 Python 中的循环导入错误。比如说,如果你在你的 site.models
模块里有某些内容,同时又在 site.views
中尝试使用 from site.models.account import User
,这就会导致循环依赖。简单来说,这种情况会让在出错的导入语句下面的内容变得未定义。如果你找不到循环导入的问题,请更新你的提问,列出所有 site.models
和 site.views
被导入的地方。