Flask and SQLAlchemy and the MetaData object

[亡魂溺海] 提交于 2019-12-03 17:07:47

Have you seen this snippet in the SQLAlchemy docs?

Maybe this would work:

# This is fine as a global global
metadata = MetaData()

@app.before_first_request
def autoload_tables():
    meta.reflect(bind=g.db.bind)

@app.route('/')
def index():
    users_table = meta.tables['users']

That way your tables are reflected only once per process which is probably what you want. Note that your engine should be a global too, so you needn't create a new engine in @app.before_request - app creation is a more appropriate place.

If your case is very special you might need one engine per request, in which case you should consider the ThreadLocalMetaData class.

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