首页 文章

配置Flask-SQLAlchemy以使用Flask-Restless的多个数据库

提问于
浏览
11

我有一个使用Flask-SQLAlchemy的Flask应用程序,我正在尝试将其配置为使用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:db_pw@localhost:5432/db_name'
SQLALCHEMY_BINDS = {
    'db1': SQLALCHEMY_DATABASE_URI,
    'db2': 'mysql://db_user:db_pw@localhost: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)
    ...

然后我像这样点燃Flask-Restless:

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数据库获得该对象的预期JSON响应(我在SQLALCHEMY_DATABASE_URI中的凭据) .

虽然当我点击 http://localhost:5000/api/mysql_model/[id] 时,我得到 mysql_model_table 不存在错误,表明它正在查找Postgres数据库,而不是MySQL数据库 .

我在这做错了什么?

1 回答

  • 11

    由于一个简单的拼写错误,这不起作用:

    __bind_key = 'db1'
    

    本来应该

    __bind_key__ = 'db1'
    

    我已经更新了原始问题并修正了拼写错误,作为一个如何为其他人工作的例子 .

相关问题