[英]models module for flask application
I'm building a flask application foo
, up until this point this is how files are organized 我正在构建一个flask应用程序foo
,直到这一点,这就是文件的组织方式
foo
|-- app
| |-- __init__.py
| |-- models.py
|
|-- foo.py
in __init__.py
I define a function to create the app, which it is then called from foo.py
. 在__init__.py
我定义了一个函数来创建应用程序,然后从foo.py
调用foo.py
。 This is how __init__.py
looks like: 这就是__init__.py
样子:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
...
db.init_app(app)
The module models.py
imports db
and access an existing database . 模块models.py
导入db
并访问现有数据库 。 So far I've been using db.engine.execute(<...>)
to make queries, but it seems kind of inefficient. 到目前为止,我一直在使用db.engine.execute(<...>)
进行查询,但这似乎效率很低。 For example, I have a table called var
which I constantly access in my app, so I define a class in models.py
例如,我有一个名为var
的表,可以在我的应用程序中不断访问它,因此我在models.py
定义了一个类。
class Var(object):
def query ...
but I'd like to use alchemy
instead: 但我想改用alchemy
:
class Var(db.Model):
...
I tried to follow the answers here to build my application, but these are the problems I've found so far 我尝试按照此处的答案来构建我的应用程序,但这是我到目前为止发现的问题
If I insert base.metadata.reflect(db.engine)
inside the create_app
function I get an error saying I need to create a context, which doesn't make a lot of sense, since this is the the place where I'm creating it. 如果我在create_app
函数中插入base.metadata.reflect(db.engine)
收到一条错误消息,提示我需要创建一个上下文,这没有多大意义,因为这是我创建的地方它。 Of course, if I do with app.app_context(): base.metadata.reflect(db.engine)
I can get around, but then the problem is still there when I create the class Var
: 当然,如果我with app.app_context(): base.metadata.reflect(db.engine)
可以解决,但是创建类Var
时问题仍然存在:
class Var(db.Model): table = db.Model.metadata.tables['var'] class Var(db.Model): table = db.Model.metadata.tables ['var']
The dictionary is empty, so I get a KeyError
. 字典是空的,所以我得到了KeyError
。
models
to create my class Var
it also fails, because it cannot import it. 当我尝试在models
内部创建上下文以创建我的类Var
它也失败了,因为它无法导入它。 I've tried all the suggestions I've found, but none of them seems to work. 我尝试了所有发现的建议,但似乎都没有用。 Thanks for your help 谢谢你的帮助
The problem is that you're using Flask-SQLAlchemy
that, like most flask extensions, is tied with flask and, for running certain tasks, it needs a flask context but, to reflect an already existing database, you need an engine independent of any request. 问题是您正在使用Flask-SQLAlchemy
,就像大多数flask扩展一样,它与flask绑定在一起,并且为了运行某些任务,它需要flask上下文,但是要反映一个已经存在的数据库,您需要一个独立于任何数据库的引擎请求。
You could probably still use db
by using with app.app_context()
wherever you need, but it's probably better to not use Flask-SQLAlchemy
and instead use SQLAlchemy
directly and use create_engine
, like in the question you linked. 您仍然可以在任何需要的地方通过with app.app_context()
使用db
,但是最好不要使用Flask-SQLAlchemy
,而是直接使用SQLAlchemy
并使用create_engine
,就像您链接的问题一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.