[英]How to import from __init__.py with Flask
I have the following file structure for a Flask application:对于 Flask 应用程序,我有以下文件结构:
myapplication/
run.py
myapplication/
__init__.py
views/
__init__.py
models.py
...
templates/
static/
And I have initialised the database in myapplication/__init__.py
using SQLAlchemy.我已经使用 SQLAlchemy 在myapplication/__init__.py
初始化了数据库。 I want to import the database object in models.py
though I'm unsure on how to do it.我想在models.py
导入数据库对象,但我不确定如何做。
I read this answer and tried to import the database object from myapplication/__init__.py
using relative imports like this:我阅读了这个答案并尝试使用这样的相对导入从myapplication/__init__.py
导入数据库对象:
from ... import db
but I receive this error: ValueError: Attempted relative import in non-package
.但我收到此错误: ValueError: Attempted relative import in non-package
。
So how to I get to the database object in myapplication/__init__.py
for models.py
?那么如何在myapplication/__init__.py
获取models.py
的数据库对象呢? Thanks.谢谢。
Add an empty file called __init__.py
to your views
folder.将一个名为__init__.py
的空文件添加到您的views
文件夹中。 Also, I think you have a dot too many, ie it should be from .. import db
.另外,我认为您的点太多了,即它应该是from .. import db
。 The first .
第一个.
references views
and the second .
参考views
和第二个.
will reference your __init__.py
.将引用您的__init__.py
。
EDIT : I had a look at the flask stuff I did myself ( freevle ), and it seems like I never used a relative import to get at the database.编辑:我看了我自己做的烧瓶的东西( freevle ),似乎我从未使用过相对导入来获取数据库。 In stead I used the app name, ie the name of the folder your top __init__.py
is in. With freevle, I used from freevle import db
.相反,我使用了应用程序名称,即顶部__init__.py
所在文件夹的名称。对于 freevle,我使用了from freevle import db
。 Would this work for you?这对你有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.