使用绑定时使用 Flask-SQLAlchemy 创建单个 table
Create a single table using Flask-SQLAlchemy while using binds
我正在尝试在 flask-sqlalchemy 中使用相同的模型设置多个数据库
示例模型如下所示
db = flask.ext.sqlalchemy.SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_default_schema_db_uri'
app.config['SQLALCHEMY_BINDS'] = {'other_schema': ''mysql+pymysql://'+UNMAE+':'+PASS+'@'+SERVERURL+':3306/'+ DBNAME,'##your_other_db_uri}
class TableA(db.Model):
# This belongs to Default schema, it doesn't need specify __bind_key__
...
class TableB(db.Model) :
# This belongs to other_schema
__bind_key__ = 'other_schema'
...
db.create_all()
工作正常并在各自的模式中创建 table。
我正在关注 并想创建一个 table 使用:
TableB.__table__.create(db.session.bind, checkfirst=True)
table 是在默认绑定中创建的,而不是 other_schema。
我在这里遗漏了什么吗?我该如何修复它以便它在其他模式中创建。
至少对于PG我是这样的:
class TableB(db.Model):
__table_args__ = {"schema":"schema_name"}
您需要为 create
函数提供正确的引擎。可以通过以下方式检索正确的绑定:
from sqlalchemy.orm import object_mapper
TableB.__table__.create(db.session().get_bind(object_mapper(TableB())), checkfirst=True)
我正在尝试在 flask-sqlalchemy 中使用相同的模型设置多个数据库
示例模型如下所示
db = flask.ext.sqlalchemy.SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_default_schema_db_uri'
app.config['SQLALCHEMY_BINDS'] = {'other_schema': ''mysql+pymysql://'+UNMAE+':'+PASS+'@'+SERVERURL+':3306/'+ DBNAME,'##your_other_db_uri}
class TableA(db.Model):
# This belongs to Default schema, it doesn't need specify __bind_key__
...
class TableB(db.Model) :
# This belongs to other_schema
__bind_key__ = 'other_schema'
...
db.create_all()
工作正常并在各自的模式中创建 table。
我正在关注
TableB.__table__.create(db.session.bind, checkfirst=True)
table 是在默认绑定中创建的,而不是 other_schema。
我在这里遗漏了什么吗?我该如何修复它以便它在其他模式中创建。
至少对于PG我是这样的:
class TableB(db.Model):
__table_args__ = {"schema":"schema_name"}
您需要为 create
函数提供正确的引擎。可以通过以下方式检索正确的绑定:
from sqlalchemy.orm import object_mapper
TableB.__table__.create(db.session().get_bind(object_mapper(TableB())), checkfirst=True)