I'm building a flask application foo
, up until this point this is how files are organized
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
. This is how __init__.py
looks like:
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. So far I've been using db.engine.execute(<...>)
to make queries, but it seems kind of inefficient. For example, I have a table called var
which I constantly access in my app, so I define a class in models.py
class Var(object):
def query ...
but I'd like to use alchemy
instead:
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 thecreate_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. Of course, if I dowith app.app_context(): base.metadata.reflect(db.engine)
I can get around, but then the problem is still there when I create the classVar
:class Var(db.Model): table = db.Model.metadata.tables['var']
The dictionary is empty, so I get a KeyError
.
- When I try to create a context inside
models
to create my classVar
it also fails, because it cannot import it.
I've tried all the suggestions I've found, but none of them seems to work. Thanks for your help