【无标题】

一.前言

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

相关推荐
敲键盘的小夜猫34 分钟前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
高压锅_12201 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django
胖达不服输2 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩2 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
吴佳浩3 小时前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm
叶 落3 小时前
计算阶梯电费
python·python 基础·python 入门
Python大数据分析@4 小时前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七4 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
Zonda要好好学习5 小时前
Python入门Day4
java·网络·python
小龙在山东5 小时前
Python 包管理工具 uv
windows·python·uv