我遇到使用Flask-SQLAlchemy在Many-to-many multi-database join with Flask-SQLAlchemy中使用多个数据库连接进行多对多连接的问题,但稍微扭曲一点,一个数据库连接是一个sqlite数据库,另一个连接到MySQL。 / p>
所以代码看起来像
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'user.db')
app.config['SQLALCHEMY_BINDS'] = {
'db0': app.config['SQLALCHEMY_DATABASE_URI'],
'db1': 'mysql://user:pass@localhost/vendor'
}
db = SQLAlchemy(app)
user_products_tbl = db.Table('user_products', db.metadata,
db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')),
db.Column('product_id', db.Integer, db.ForeignKey('products.product_id')),
schema='main',
info={'bind_key': 'db0'},
)
class Product(db.Model):
__bind_key__ = 'db1'
__tablename__ = 'products'
id = db.Column('product_id', db.Integer, primary_key=True)
name = db.Column(db.String(120))
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Product %r>' % self.name
class User(db.Model):
__bind_key__ = 'db0'
__tablename__ = 'users'
id = db.Column('user_id', db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
products = db.relationship("Product", secondary=user_products_tbl,
backref="users", lazy="dynamic")
def __init__(self, username, products):
self.username = username
self.products = products
def __repr__(self):
return '<User %r>' % self.username
在我尝试添加新用户之前,一切都很好。
>>> from app import db, User, Product
>>> db.create_all()
>>> product = Product('prod')
>>> db.session.add(product)
>>> db.session.commit()
>>> user = User('Admin',[product])
>>> db.session.add(user)
>>> db.session.commit()
Traceback (most recent call last):
...
File " .../venv/lib/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'main.user_products' doesn't exist") 'INSERT INTO main.user_products (user_id, product_id) VALUES (%s, %s)' (1, 1L)
所以sqlalchemy最终使用MySQL连接为user_products表。我相信这是sqlalchemy如何使用多个数据库驱动程序处理作用域会话的错误,但我还没有找到解决方案。