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
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.Laden Sie 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()
model.py
from database import db
class SecondSample(db.Model):
__bind_key__ = 'second_sample_db' #config.Was wurde mit py eingestellt
__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
Referenz: Ich möchte mit flask_sqlalchemy eine Verbindung zu mehreren Datenbanken herstellen
Recommended Posts