I'm coding a project with Flask and Flask-SQLAlchemy, and in that project, I need to access unknown databases, and in those databases, execute queries with db.engine.execute(<SQL>).
But how can I specify which database will receive the query?
Example:
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)
How can I run show tables; In db1? And in db2?