Skip to content

Instantly share code, notes, and snippets.

@sp3c73r2038
Last active May 24, 2021 11:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sp3c73r2038/5925631 to your computer and use it in GitHub Desktop.
Save sp3c73r2038/5925631 to your computer and use it in GitHub Desktop.
how to acccess multiple database with same tablename, in Flask and SQLAlchemy.
# -*- 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()
# -*- 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