【无标题】

一.前言

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

相关推荐
ZH154558913110 分钟前
Flutter for OpenHarmony Python学习助手实战:面向对象编程实战的实现
python·学习·flutter
玄同76511 分钟前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
User_芊芊君子16 分钟前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
白日做梦Q27 分钟前
Anchor-free检测器全解析:CenterNet vs FCOS
python·深度学习·神经网络·目标检测·机器学习
喵手41 分钟前
Python爬虫实战:公共自行车站点智能采集系统 - 从零构建生产级爬虫的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集公共自行车站点·公共自行车站点智能采集系统·采集公共自行车站点导出csv
喵手1 小时前
Python爬虫实战:地图 POI + 行政区反查实战 - 商圈热力数据准备完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·地区poi·行政区反查·商圈热力数据采集
熊猫_豆豆1 小时前
YOLOP车道检测
人工智能·python·算法
nimadan121 小时前
**热门短剧小说扫榜工具2025推荐,精准捕捉爆款趋势与流量
人工智能·python
默默前行的虫虫1 小时前
MQTT.fx实际操作
python
YMWM_1 小时前
python3继承使用
开发语言·python