python - flask-sqlalchemy怎么操作postgresql中不同schema(默认是public)

 城哥_1986 发布于 2022-10-28 17:49

1.现在我的postgresql中有多个schema

现在使用sqlalchemy中URI
postgresql://postgres:111111@127.0.0.1:5432/db
连接上的数据库中默认是在public这个schema下的,
我怎么使用stage这个schema呢?

2 个回答
  • 2种情况:

    1: 手工定义模型

    class Test(db.Model):
        __tablename__ = 'test'
        __table_args__ = {
            'schema': 'other_schema'
        }
        id = db.Column('test_id', db.String(12), primary_key=True, )
        name = db.Column('test_name', db.String(10))
    

    手工定义模型时,加上__table_args__参数 指定model使用的schema

    2: 反射schema中的一个表到Model中

    我用的是工厂函数生成Flask实例的。

    工厂函数中:

    def create_app(config_name):
        app = Flask(__name__)
        app.config.from_object(config[config_name])
        CORS(app)
        config[config_name].init_app(app)
        db.init_app(app)
        # 总觉得这里的实现不是很好 有更好的解决方案请告知
        tables = [‘test’]
        op = getattr(db.Model.metadata, ‘reflect’)
        op(bind=db.get_engine(app), only=tables, schema=’other_schema’)
    
        login_manager.init_app(app)
        from .hello import hello
        from .auth import auth
        app.register_blueprint(hello)
        app.register_blueprint(auth)
    
        return app
    

    反射模型定义中:

    class Test(db.Model):
        __tablename__ = ‘other_schema.test’
        
        # 有时后数据表设计时没有主键,但SQLAlchemy需要有主键,对于这类表我们需要重新指定主键:
        # 这里有时候需要用 __mapper_args__ 指定这张表的primary_key是哪个
        __mapper_args__ = {
        ‘primary_key’: [db.Model.metadata.tables[‘other_schema.test’].c.id]
        }
    

    然后就可以通过orm的方式去操作其他schema的表了,被这个问题折腾了大半天了,希望能帮到有需要的人。

    2022-10-30 01:54 回答
  • 查询表的时候,带上 schema 前缀,例如

     select xxx from stage.table_name where ...; 
    2022-10-30 02:39 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有