【无标题】

一.前言

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

相关推荐
程序设计实验室4 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三6 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427119 小时前
Python之语言特点
python
刘立军9 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机13 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机14 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i15 小时前
django中的FBV 和 CBV
python·django
c8i15 小时前
python中的闭包和装饰器
python
这里有鱼汤18 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列