【无标题】

一.前言

在使用 FastAPI 和 MySQL 数据库时,异步连接可以显著提高应用程序的性能和响应速度。为了实现这一点,可以使用 aiomysql 或 asyncmy 库来处理异步数据库操作。

二.安装使用

1. 安装依赖

python 复制代码
pip install fastapi uvicorn aiomysql sqlalchemy[asyncio]

2.代码示例【demo】

python 复制代码
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.dialects.mysql import BIGINT, INTEGER, TINYINT
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import select, text, Column, String, Text, DateTime, func
from pydantic import BaseModel
from datetime import datetime

from configure.configure import config

app = FastAPI()

# 创建异步数据库引擎
DATABASE_URL = f"mysql+aiomysql://root:root@{config['mysql']['host']}:{config['mysql']['port']}/{config['mysql']['database']}"

engine = create_async_engine(
    DATABASE_URL,
    pool_size=50,  # 连接池大小
    max_overflow=100,  # 超出 pool_size 的最大连接数
    pool_recycle=3600,  # 自动回收空闲连接的时间(秒),设置为 0 则禁用该功能
    pool_timeout=10,
    echo=False
)

# 创建异步会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)

# 声明基类
Base = declarative_base()


# 定义模型
class NwSessionHistory(Base):
    __tablename__ = 'nw_session_history'

    id = Column(BIGINT(20), primary_key=True)
    name = Column(String(255), nullable=False, server_default=text("''"))
    create_time = Column(DateTime, nullable=False, default=func.now())


# Pydantic 模型
class SearchParams(BaseModel):
    page: int = 0
    pagesize: int = 10


# 用于创建新记录的 Pydantic 模型
class CreateNwSessionHistory(BaseModel):
    name: str


# 用于更新记录的 Pydantic 模型
class UpdateNwSessionHistory(BaseModel):
    name: str


# 依赖注入
async def get_db() -> AsyncSession:
    async with SessionLocal() as session:
        try:
            yield session
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))


# 异步查询函数
async def search(dbSession: AsyncSession, page: int = 0, pagesize: int = 10, **kv_cond):
    # 1千万条大数据查询接口
    sql = "SELECT * FROM TABLE"
    res = await dbSession.execute(text(sql))
    return res.fetchall()


# 路由
@app.post('/search')
async def search_route(params: SearchParams, dbSession: AsyncSession = Depends(get_db)):
    print('request', params)
    res = await search(dbSession, params.page, params.pagesize)
    return {'res': res[0]}


# 查询记录
async def search_session_history(dbSession: AsyncSession, page: int = 0, pagesize: int = 10):
    query = (
        select(NwSessionHistory)
        .where(NwSessionHistory.create_time.between('2024-09-03', '2025-09-03'))
        .offset(page * pagesize)
        .limit(pagesize)
    )
    res = await dbSession.execute(query)
    return res.scalars().all()


# 路由
@app.post('/search_model')
async def search_route(page: int = 0, pagesize: int = 10, dbSession: AsyncSession = Depends(get_db)):
    print('request', page, pagesize)
    res = await search_session_history(dbSession, page, pagesize)
    return res


# 创建记录
@app.post("/create")
async def create_record(record: CreateNwSessionHistory, dbSession: AsyncSession = Depends(get_db)):
    new_record = NwSessionHistory(name=record.name)
    dbSession.add(new_record)
    await dbSession.commit()
    await dbSession.refresh(new_record)
    return new_record


# 更新记录
@app.put("/update/{record_id}")
async def update_record(record_id: int, record: UpdateNwSessionHistory, dbSession: AsyncSession = Depends(get_db)):
    # 查询记录是否存在
    existing_record = await dbSession.get(NwSessionHistory, record_id)
    if not existing_record:
        raise HTTPException(status_code=404, detail="Record not found")

    # 更新记录
    existing_record.name = record.name
    await dbSession.commit()
    await dbSession.refresh(existing_record)
    return existing_record


# 删除记录
@app.delete("/delete/{record_id}")
async def delete_record(record_id: int, dbSession: AsyncSession = Depends(get_db)):
    # 查询记录是否存在
    existing_record = await dbSession.get(NwSessionHistory, record_id)
    if not existing_record:
        raise HTTPException(status_code=404, detail="Record not found")

    # 删除记录
    await dbSession.delete(existing_record)
    await dbSession.commit()
    return {"message": "Record deleted successfully"}


if __name__ == "__main__":
    import uvicorn

    host = "0.0.0.0"
    port = 8000
    uvicorn.run("app:app", host=host, port=port)

以上就是设置 FastAPI 和 MySQL 数据库之间异步连接的基本使用示例。希望对你有所帮助!

相关推荐
悠哉悠哉愿意10 分钟前
【电赛学习笔记】MaixCAM 的OCR图片文字识别
笔记·python·嵌入式硬件·学习·视觉检测·ocr
nbsaas-boot37 分钟前
SQL Server 窗口函数全指南(函数用法与场景)
开发语言·数据库·python·sql·sql server
Catching Star37 分钟前
【代码问题】【包安装】MMCV
python
摸鱼仙人~38 分钟前
Spring Boot中的this::语法糖详解
windows·spring boot·python
Warren9841 分钟前
Java Stream流的使用
java·开发语言·windows·spring boot·后端·python·硬件工程
点云SLAM2 小时前
PyTorch中flatten()函数详解以及与view()和 reshape()的对比和实战代码示例
人工智能·pytorch·python·计算机视觉·3d深度学习·张量flatten操作·张量数据结构
爱分享的飘哥2 小时前
第三篇:VAE架构详解与PyTorch实现:从零构建AI的“视觉压缩引擎”
人工智能·pytorch·python·aigc·教程·生成模型·代码实战
进击的铁甲小宝3 小时前
Django-environ 入门教程
后端·python·django·django-environ
落魄实习生3 小时前
UV安装并设置国内源
python·uv
阿克兔3 小时前
建筑兔零基础python自学记录114|正则表达式(1)-18
python