python - flask-sqlalchemy怎么操作postgresql中不同schema(默认是public)
ringa_lee
ringa_lee 2017-04-17 17:39:22
0
2
1087

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

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

ringa_lee
ringa_lee

ringa_lee

全部回覆(2)
巴扎黑

查詢表的時候,帶上 schema 前綴,例如

 select xxx from stage.table_name where ...; 
左手右手慢动作

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的表了,被​​這個問題折騰了大半天了,希望能幫到有需要的人。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!