Flask and SQLAlchemy, application not registered on instance

岁酱吖の 提交于 2019-11-30 10:03:57
Rachel Sanders

The answer is here: http://flask-sqlalchemy.pocoo.org/latest/api/#configuration

See the part about:

The difference between the two is that in the first case methods like create_all() and drop_all() will work all the time but in the second case a flask.Flask.request_context() has to exist.

There's more information here: http://flask-sqlalchemy.pocoo.org/latest/contexts/

If all that is confusing (it probably is, since it's talking about a fairly advanced feature of Flask), the short short version is db.init_app(app) changes the app object, but it doesn't change anything in the db object. It's on purpose because there might be more than one app flying around, and db might have to talk to all of them. (I said it was an advanced feature.)

So when you call db.create_all() without having a request live (which creates a global that has the currently running app) it doesn't know what to connect to, and bombs. That's what the error means.

In your case, I would put the SQLAlchemy call back in __init__.py and pass app to it, that's the easiest way:

db = SQLAlchemy(app)

Or keep things as they are, and run the setup before the first request:

@app.before_first_request
def create_database():
     db.create_all()

I hope that helps! Let me know if you run into any more problems.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!