【无标题】

一.前言

在使用 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 数据库之间异步连接的基本使用示例。希望对你有所帮助!

相关推荐
码云骑士2 分钟前
26-密码密钥配置管理-env文件与多环境隔离策略
python
装不满的克莱因瓶3 分钟前
掌握基于YOLO v5实现车牌目标检测任务的完整流程——从数据到部署的工业级实践
人工智能·python·深度学习·yolo·目标检测·计算机视觉·目标跟踪
骑士雄师4 分钟前
1.1 rag开发基础配置
python
码云骑士5 分钟前
25-数据库连接池-Django连接复用与连接数上限控制
数据库·python·django
叫我:松哥6 分钟前
基于Flask的在线考试刷题系统设计与实现,集智能练习、过程追踪、深度分析与个性化引导
数据库·人工智能·后端·python·flask·boostrap
techdashen7 分钟前
CPython 仓库 Top 100 贡献者深度分析
python
码云骑士12 分钟前
22-接手Django老项目(下)-读懂urls路由树与架构脉络
python·架构·django
码云骑士13 分钟前
29-Python-logging日志模块-print不是日志的生产级实战
开发语言·python
Attachment George21 分钟前
山东大学软件学院-项目实训-个人开发日志(十):材料问答链路开发——文档解析、OCR兜底与持续追问完善
python·ai·langchain·kotlin·rag
码云骑士21 分钟前
24-Django请求全链路-WSGI到数据库响应的完整旅程
数据库·python·django