Last active
May 24, 2021 11:51
-
-
Save sp3c73r2038/5925631 to your computer and use it in GitHub Desktop.
how to acccess multiple database with same tablename, in Flask and SQLAlchemy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from flask import Flask | |
from sqlalchemy import SQLAlchemy | |
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+oursql://foo:bar@localhost/test1" | |
# binds multiple database definition | |
app.config['SQLALCHEMY_BINDS'] = { | |
"db1": "mysql+oursql://foo:bar@localhost/test1", | |
"db2": "mysql+oursql://foo:bar@localhost/test2" | |
} | |
class Application(Flask): | |
def ready(): | |
db1.init_app(self) | |
db2.init_app(self) | |
# create multiple sqlalchemy engines | |
db1 = SQLAlchemy() | |
db2 = SQLAlchemy() | |
app = Application() | |
# code in program start point | |
from app import app | |
from app.models import User, AnotherUser | |
@app.route('/') | |
def index(): | |
# | |
# User.query(...) | |
# AnotherUser.query(...) | |
pass | |
app.ready() | |
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from sqlalchemy import Column | |
from app import db1, db2 | |
class User(db1.Model): | |
# | |
# id = ... | |
# | |
__tablename__ = 'users' | |
__bind_key__ = 'test1' # read from database 'test1' | |
# SHOULD use different sqlalchemy engine | |
# otherwise, it will cause | |
# | |
# sqlalchemy.exc.InvalidRequestError: Table 'users' is already | |
# defined for this MetaData instance. Specify 'extend_existing=True' | |
# to redefine options and columns on an existing Table object. | |
# | |
class AnotherUser(db2.Model): | |
# | |
# id = ... | |
# | |
__tablename__ = 'users' | |
__bind_key__ = 'test2' # read from database 'test2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment