flask-sqlalchemy:无法连接来自两个数据库的表(不同的绑定键)。收到错误1146(请参阅下文)

凯尔斯滕

我正在使用python和sqlalchemy构建Flask-Restful API,并且尝试连接来自不同数据库的两个表。看来我一次只能搜索一个数据库中的表。我想念什么吗?

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request 

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@host:8000/database1'
app.config['SQLALCHEMY_BINDS'] = {
    'database2': 'mysql://username:password@host:8000/database2'
}


db = SQLAlchemy(app)
db.create_all(bind='database2')

class Table1(db.Model):
    __tablename__ = "table1"
    __table_args__ = {'schema':'database1'}
    location_id = db.Column(db.Integer, primary_key=True)

    def __init__(self, location_id):
        self.location_id = location_id
    def __repr__(self):
        return '{}'.format(self.location_id)

class Table2(db.Model):
    __bind_key__ = "database2"
    __tablename__ = "table2"
    __table_args__ = {'schema':'database2'}
    other_id = db.Column(db.Integer, primary_key=True)
    location_id = db.Column(db.Integer, db.ForeignKey('database1.table1.location_id'))

    def __init__(self, other_id, location_id):
        self.other_id = other_id
        self.location_id = location_id

    def __repr__(self):
        return '{}'.format(self.other_id)


@app.route('/', methods=['GET'])
def returnRes():
    session = db.session
    q = session.query(table1).join(table2, table1.location_id==table2.location_id).all()
return str(q)

在我的浏览器中,出现错误: 'sqlalchemy.exc.ProgrammingError: (_mysql_exceptions.ProgrammingError) (1146, "Table 'database1.table2' doesn't exist").

这两个表确实存在,因为当我将查询更改为时,出现 q = session.query(table2).join(table1, table2.location_id==table1.location_id).all() 一个错误,指出database2.table1不存在。

我正在使用python == 3.6.1,Flask == 0.11.1和Flask-SQLAlchemy == 2.1

凯尔斯滕

在我的表类中添加数据库架构参数并添加外键可解决此问题。我在此链接上找到了答案:https : //github.com/mitsuhiko/flask-sqlalchemy/issues/172

我已经更新了问题以反映答案,以防其他人受益。

我不确定绑定是否多余,但是我将它们留在了里面,因为它们似乎没有任何干扰。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章