我正在使用Flask和Flask-SQLAlchemy对项目进行编码,在该项目中,我需要访问未知数据库,并在这些数据库中使用db.engine.execute(<SQL>)
执行查询。
但是如何指定哪个数据库将接收查询?
示例:
app = Flask(__name__, static_url_path="")
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:******@127.0.0.1:3306/api'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_BINDS'] = {
'db1': 'mysqldb://localhost/users',
'db2': 'sqlite:////path/to/appmeta.db'
}
api = Api(app)
auth = HTTPBasicAuth()
db = SQLAlchemy()
db.init_app(app)
@app.before_first_request
def create_database():
db.drop_all()
db.create_all()
@app.route('/test')
def test():
result = db.engine.execute("show tables;")
names = []
for row in result:
names.append(row[0])
return str(names)
如何在db1中运行show tables;
?在db2?
答案 0 :(得分:1)
您可以在Flask-SQLAlchemy中使用get_engine()
方法:
engine_db1 = db.get_engine(app, 'db1')
engine_db2 = db.get_engine(app, 'db2')
sql = text("SHOW TABLES")
results_db1 = engine_db1.execute(sql)
results_db2 = engine_db2.execute(sql)