【问题标题】:Configuring Flask-SQLAlchemy to use multiple databases with Flask-Restless使用 Flask-Restless 配置 Flask-SQLAlchemy 以使用多个数据库
【发布时间】:2013-02-07 21:36:37
【问题描述】:

我有一个使用 Flask-SQLAlchemy 的 Flask 应用程序,我正在尝试将其配置为通过 Flask-Restless 包使用多个数据库。

根据the docs,通过__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 它需要使用哪个数据库:

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 DB 中获得了对象的预期 JSON 响应(我猜这是因为我在 SQLALCHEMY_DATABASE_URI 中有它的凭据)。

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

我在这里做错了什么?

【问题讨论】:

    标签: python flask flask-sqlalchemy


    【解决方案1】:

    由于一个简单的错字,这不起作用:

    __bind_key = 'db1'
    

    应该是

    __bind_key__ = 'db1'
    

    我已经更新了原始问题并修正了错字,以此作为对其他人如何工作的示例。

    【讨论】:

    • 如何访问模型的 bind_key 以获取该模型的数据库名称?
    猜你喜欢
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2016-09-13
    • 2015-07-29
    • 2022-07-08
    • 2017-09-20
    • 2018-06-13
    相关资源
    最近更新 更多