在项目我们经常需要,多个数据库之间的数据交叉使用。在django中,可以在settings 文件中配置,比较简单,但是在fastapi 中如何解决呢
django 中使用方法:
- settings.py
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2','NAME': POSTDB,'USER': 'postgres','PASSWORD': '***','HOST': '****111','PORT': '5432',"CONN_MAX_AGE": 60, # 60秒},'109': {'ENGINE': 'django.db.backends.postgresql_psycopg2','NAME': 'companyinfodb','USER': 'postgres','PASSWORD': '*****','HOST': '*****1109','PORT': '5432',"CONN_MAX_AGE": 60, # 60秒},
}
- views.py
# 在使用中需要使用using()来指定数据源
dwd_ = CompetitiveNoteInfoDetail.objects.using('109').filter(id=j_id).first()
- models.py 中不需要特殊的设置
fastapi中使用方法:
- settings/settings.py
TORTOISE_CONFIG = {'connections': {# Dict format for connection'default': {'engine': 'tortoise.backends.asyncpg','credentials': {'host': POSTGRES_HOST,'port': '5432','user': POSTGRES_USER,'password': POSTGRES_PWD,'database': POSTDB,}},'111': {'engine': 'tortoise.backends.asyncpg','credentials': {'host': '10.10.25.111','port': '5432','user': 'postgres','password': 'feng1991','database': 'feijiu_business_online',}},# Using a DB_URL string# 'default': f'postgres://{POSTGRES_USER}:{POSTGRES_PWD}@{POSTGRES_HOST}:5432/{POSTDB}'},'apps': {'models': {"models": [MODEL_PATH],'default_connection': 'default',},'models_111': {"models": [MODEL_PATH],'default_connection': '111',}},'use_tz':False,'timezone':'Asia/Shanghai',}
- main.py
app = FastAPI(debug=DEBUG,title=TITLE,description=DESCRIPTION,docs_url=DOCS_URL,openapi_url=OPENAPI_URL,redoc_url=REDOC_URL,dependencies=[Depends(verify_token), ])register_tortoise(app,# db_url=DB_URL,# modules={"models": [MODEL_PATH]},config=TORTOISE_CONFIG,generate_schemas=False,add_exception_handlers=False,
)
- models.py
class WasteAssetInfoTable(models.Model):"""废旧资产表--所有已发布的帖子不管申领与否都应该出现在这个表中"""STATUS_NORMAL = 1STATUS_DELETE = 0STATUS_ITEMS = ((STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'))id = fields.UUIDField(pk=True, default=uuid.uuid4, editable=False)title = fields.TextField(verbose_name='帖子标题', default='', null=True, blank=True)desc = fields.TextField(verbose_name='帖子描述', default='', null=True, blank=True)status = fields.IntField(default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态")update_time = fields.DatetimeField(auto_now=True, verbose_name='更新时间')del_time = fields.DatetimeField(default=None, verbose_name='删除时间', null=True, blank=True)delete_time = fields.DatetimeField(default=None, verbose_name='删除时间2', null=True, blank=True)created_time = fields.DatetimeField(auto_now_add=True, verbose_name='创建时间',db_index=True)class Meta:description = description_plural = '废旧资产表'table = 'waste_asset_info_table'app = 'models_111' # 此处需要制定app 来制定使用的是那个数据源
- views.py
# 此处与django不同,不需要使用using('111'), 直接filter 即可result = await WasteAssetInfoTable.filter(user_phone=company_phone).values('title','user_name', 'user_phone','source', 'is_dj')