我有一個使用Flask-SQLAlchemy的Flask應用程序,我試圖配置它使用Flask-Restless包中的多個數據庫。配置Flask-SQLAlchemy與Flask-Restless一起使用多個數據庫
根據文檔(http://pythonhosted.org/Flask-SQLAlchemy/binds.html),將模型配置爲使用__bind_key__
的多個數據庫似乎非常簡單。
但它似乎並沒有爲我工作。
創建我的應用程序,並初始化我的數據庫是這樣的:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'postgres://db_user:[email protected]:5432/db_name'
SQLALCHEMY_BINDS = {
'db1': SQLALCHEMY_DATABASE_URI,
'db2': 'mysql://db_user:[email protected]:3306/db_name'
}
app = Flask(__name__)
db = SQLALchemy(app)
然後確定我的模型,包括__bind_key__
,這應該告訴SQLAlchemy的其中DB它需要使用:
class PostgresModel(db.Model):
__tablename__ = 'postgres_model_table'
__bind_key__ = 'db1'
id = db.Column(db.Integer, primary_key=True)
...
class MySQLModel(db.Model):
__tablename__ = 'mysql_model_table'
__bind_key__ = 'db2'
id = db.Column(db.Integer, primary_key=True)
...
然後我火像這樣燒瓶不安:
manager = restless.APIManager(app, flask_sqlalchemy_db=db)
manager.init_app(app, db)
auth_func = lambda: is_authenticated(app)
manager.create_api(PostgresModel,
methods=['GET'],
collection_name='postgres_model',
authentication_required_for=['GET'],
authentication_function=auth_func)
manager.create_api(MySQLModel,
methods=['GET'],
collection_name='mysql_model',
authentication_required_for=['GET'],
authentication_function=auth_func)
該應用運行良好,當我點擊http://localhost:5000/api/postgres_model/[id]
時,我得到Postgres DB對象的預期JSON響應(我猜這是因爲我在SQLALCHEMY_DATABASE_URI中擁有它的憑據)。
雖然當我點擊http://localhost:5000/api/mysql_model/[id]
,我得到一個mysql_model_table
不存在的錯誤,表明它正在尋找Postgres DB,而不是MySQL。
我在這裏做錯了什麼?