Flask-SqlAlchemy 视图反射
SQLAlchemy 类里面有一个叫做 reflect 的方法:
reflect(bind='__all__', app=None)
Reflects tables from the database.
这个方法只有两个参数:bind 和 app。我在 metadata.tables
里没有找到任何视图。
原生的 SQLAlchemy 的 reflect 方法有更多的参数,其中有一个是 views=False,如果把它设置为 True,就可以反映出视图。
reflect(bind=None, schema=None, views=False, only=None, extend_existing=False, autoload_replace=True, **dialect_kwargs)
那么,在 Flask-SQLAlchemy 中,有没有办法反映出数据库的视图呢?
1 个回答
3
你可以创建一个SQLAlchemy类的子类,并重写其中的某个函数。这是在Flask中进行自定义的常用方法。Flask的文档里也提到过,可以通过子类化Flask类来实现你需要的功能。
这个方法还没有经过测试,但可以作为一个起点。它允许你在执行和反射时传递一些额外的参数,并将这些参数传递给真正的操作。
class MySQLAlchemy(SQLAlchemy):
def _execute_for_all_tables(self, app, bind, operation, **kwargs):
app = self.get_app(app)
if bind == '__all__':
binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ())
elif isinstance(bind, basestring) or bind is None:
binds = [bind]
else:
binds = bind
for bind in binds:
tables = self.get_tables_for_bind(bind)
op = getattr(self.Model.metadata, operation)
op(bind=self.get_engine(app, bind), tables=tables, **kwargs)
def reflect(self, bind='__all__', app=None, **kwargs):
self._execute_for_all_tables(app, bind, 'reflect', **kwargs)