我建立使用Python和SQLAlchemy的燒瓶中的RESTful API,我試圖加入來自不同數據庫的兩個表。看來,我一次只能在一個數據庫中搜索表。我錯過了什麼嗎?燒瓶-SQLAlchemy的:故障從兩個數據庫(不同的綁定密鑰)連接表。收到錯誤1146(見下文)
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:[email protected]:8000/database1'
app.config['SQLALCHEMY_BINDS'] = {
'database2': 'mysql://username:[email protected]: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,瓶== 0.11.1和燒瓶的SQLAlchemy == 2.1
你能否證實這兩個表實際上存在嗎? – ACV
是的,他們都存在。請參閱上面的編輯進行說明。 – Kairsten
這些似乎是相關的答案:https://stackoverflow.com/questions/44564369/join-tables-in-two-databases-using-sqlalchemy; https://stackoverflow.com/questions/9416871/qualifying-table-names-with-database-names-in-sqlalchemy – ACV