[PYTHON] Connect to multiple databases with SQLAlchemy

DB information settings

config.py


class SystemConfig:

    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{password}@{host}/{db_name}?charset=utf8'.format(**{
        'user': 'sample_user',
        'password': 'passwd',
        'host': 'host',
        'db_name': 'sample_db_1'
    })
    
    SQLALCHEMY_BINDS = {"second_sample_db": SECOND_SAMPLE_DATABASE}

    SECOND_SAMPLE_DATABASE = 'mysql+pymysql://{user}:{password}@{host}/{db_name}?charset=utf8'.format(**{
        'user': 'sample_user',
        'password': 'passwd',
        'host': 'host',
        'db_name': 'sample_db_2'
    })

Config = SystemConfig

File settings at startup

database.py


from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def init_db(app):
  db.init_app(app)

__init__.py


import config

from flask import Flask
from api.database import db


def create_app():

    app = Flask(__name__)

    # config.Load py
    app.config.from_object('config.Config')
    db.init_app(app)

    return app

app = create_app()

app.py


from api import app

if __name__ == '__main__':
  app.run()

DB model

model.py


from database import db

class SecondSample(db.Model):
    __bind_key__ = 'second_sample_db' #config.What was set with py
    __tablename__ = 'second_sample_table'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    date = db.Column(db.DATETIME)

    def __init__(self, id, name, date):
        self.id = id
        self.name = name
        self.date = date

Reference: I want to connect to multiple databases with flask_sqlalchemy

Recommended Posts

Connect to multiple databases with SQLAlchemy
How to use SQLAlchemy / Connect with aiomysql
Connect to BigQuery with Python
Connect to Wikipedia with Python
Connect to Postgresql with GO
Introduction to RDB with sqlalchemy Ⅰ
How to update with SQLAlchemy?
How to Alter with SQLAlchemy?
How to Delete with SQLAlchemy?
Introduction to RDB with sqlalchemy II
Connect to Bitcoin Testnet with Pycoin
Connect to Elastic MQ with boto
How to INNER JOIN with SQLAlchemy
Connect to MySQL using Flask SQLAlchemy
How to title multiple figures with matplotlib
How to get parent id with sqlalchemy
Connect to MySQL with Python within Docker
Connect to GNU / Linux with Remote Desktop
Connect to s3 with AWS Lambda Python
Connect to pepper with PEPPER Mac's python interpreter
I get a UnicodeDecodeError when trying to connect to oracle with python sqlalchemy
Connect to mysql
I want to display multiple images with matplotlib.
[Python] How to draw multiple graphs with Matplotlib
Easily log in to AWS with multiple accounts
Easily connect Xillybus to user logic with cReComp
[Python] Mention to multiple people with Slack API
Connect to MySQL with Python on Raspberry Pi
How to return multiple indexes with index method
Multiple selections with Jupyter
Convert 202003 to 2020-03 with pandas
How to convert a class object to a dictionary with SQLAlchemy
How to get more than 1000 data with SQLAlchemy + MySQLdb
Write multiple records to DynamoDB with Lambda (Python, JavaScript)
Connect python to mysql
Use Enums with SQLAlchemy
Summary of how to share state with multiple functions
How to embed multiple embeds in one message with Discord.py
How to connect to various DBs from Python (PEP 249) and SQLAlchemy
Connect to centos6 on virtualbox with ssh connection from Mac
Connect the Jupyter Notebook kernel to Spyder with Jupytext enabled
I wanted to delete multiple objects in s3 with boto3
Connect Raspberry Pi to Alibaba Cloud IoT Platform with Python
I tried to create an article in Wiki.js with SQLAlchemy
Try to factorial with recursion
Get table dynamically with sqlalchemy
Multiple regression analysis with Keras
Use DATE_FORMAT with SQLAlchemy filter
Post to slack with Python 3
Output to syslog with Loguru
Easy to make with syntax
Connect Vagrant's MySQL with MySQL Workbench
Manipulate multiple proxies with Squid
To run gym_torcs with ubutnu16
Browse columns encrypted with sqlalchemy
How to cast with Theano
Manipulate various databases with Python
Connect to sqlite from python
Switch python to 2.7 with alternatives
Write to csv with Python
How to separate strings with','