python - Flask-SqlAlchemy View 反射

标签 python flask sqlalchemy flask-sqlalchemy

SQLAlchemy 类具有方法reflect:

 reflect(bind='__all__', app=None)

    Reflects tables from the database.

它只有 2 个参数:bind 和 app。我在 metadata.tables 中找不到任何 View 。

原生SqlAlchemy的方法reflect有更多参数,views=False是其中之一,如果设置为True,则允许 View 反射。

reflect(bind=None, schema=None, views=False, only=None, extend_existing=False, autoload_replace=True, **dialect_kwargs)

是否可以以某种方式反射(reflect) Flask-SqlAlchemy 中的数据库 View ?

最佳答案

子类化 SQLAlchemy 类并覆盖该函数。这是 Flask 领域公认的定制方法。 Flask 文档本身讨论了对 Flask 类进行子类化以获得您需要的内容。

这尚未经过测试,但这是一个开始。它允许传递 kwargs 来执行和反射,将它们传递给真正的操作。

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)

关于python - Flask-SqlAlchemy View 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292931/

相关文章:

python - 使用 Argparse 在 Python 中创建文件转换器

python - 堆叠卷积层如何在 CNN 中工作?

python - tkinter PIL 图像未显示在类里面

python - Flask 的错误请求

python-3.x - 从 SQLAlchemy session 对象获取原始 psycopg2 游标对象

python - 有没有办法通过给定的请求格式文本来初始化 HTTP 请求?

python - 如何使用 Flask-WTForms 以 DRY 方式创建重复的表单元素?

python - Flask-sqlalchemy:何时关闭 session ?

python - 我可以找到mysql中查询返回的字段的数据类型吗

python - 如何使用 SQLAlchemy Core 通过子查询插入多个值?