from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from app.configs import config
class GetDB(object):
def _get_orm_base_conf(self, apps: dict) -> dict:
return {
'connections': {
'first': {
'engine': 'tortoise.backends.mysql',
'credentials': {
'host': config.MYSQL_HOST,
'port': config.MYSQL_PORT,
'user': config.MYSQL_USERNAME,
'password': config.MYSQL_PASSWORD,
'database': config.MYSQL_DATABASE,
'minsize': 1,
'maxsize': 5,
'charset': 'utf8mb4'
}
},
'second': "sqlite://databases.db"
},
'apps': apps,
'use_tz': False,
'timezone': 'Asia/Shanghai'
}
@property
def orm_link_conf(self) -> dict:
orm_apps_settings = {
'tournaments': {'models': ['app.models.base_model'], 'default_connection': 'second'},
'events': {'models': ['app.models.mysql_model'], 'default_connection': 'first'},
}
return self._get_orm_base_conf(orm_apps_settings)
# mysql
ORM_LINK_CONF = GetDB().orm_link_conf
def init_db(app: FastAPI):
"""init and bind tortoise-orm"""
register_tortoise(
app,
config=ORM_LINK_CONF,
generate_schemas=config.DEBUG # 启动app时候,是否自动创建数据库表格
)
在这第一个first是mysql数据,第二个second是sqlite数据库,根据实际需要可以换成对应的数据库,将两边的数据库对应的model分开存储就行