3.FastAPI ORM建表

ORM - 创建数据库引擎

使用 create_async_engine 创建异步引擎

python 复制代码
# pip install sqlalchemy[asyncio] aiomysql fastapi uvicorn
from contextlib import asynccontextmanager
from datetime import datetime
from typing import AsyncGenerator

from fastapi import FastAPI, Depends
from sqlalchemy import DateTime, func, String, Float, select
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

# ==================== 数据库配置 ====================
ASYNC_DB_URL = "mysql+aiomysql://root:123456@localhost:3306/fastapi01"

async_engine = create_async_engine(
    ASYNC_DB_URL,
    echo=True,  # 打印SQL语句,生产环境关闭
    pool_size=10,
    max_overflow=20,
)

# 异步会话工厂 通过注入执行增删改查
AsyncSessionLocal = async_sessionmaker(
    bind=async_engine,
    class_=AsyncSession,
    expire_on_commit=False,  # 提交后不失效对象,开发常用优化
)

# ==================== ORM基类 ====================
class Base(DeclarativeBase):
    # 创建时间:仅新增时自动填充
    create_time: Mapped[datetime] = mapped_column(
        DateTime, default=func.now(), comment="创建时间"
    )
    # 更新时间:新增默认填充,更新自动刷新
    update_time: Mapped[datetime] = mapped_column(
        DateTime, default=func.now(), onupdate=func.now(), comment="修改时间"
    )

class Book(Base):
    __tablename__ = "book"
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, comment="编号")
    bookname: Mapped[str] = mapped_column(String(100), comment="书名")
    author: Mapped[str] = mapped_column(String(100), comment="作者")
    price: Mapped[float] = mapped_column(Float, comment="价格")
    publisher: Mapped[str] = mapped_column(String(255), comment="出版社")

# ==================== 数据库初始化 ====================
async def create_tables():
    """启动时自动创建数据表(仅开发使用,生产使用Alembic迁移)"""
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

# 获取数据库会话依赖
async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        yield session
        await session.commit()

# ==================== FastAPI Lifespan ====================
@asynccontextmanager
async def lifespan(app: FastAPI):
    print("🚀 服务启动,初始化数据库...")
    await create_tables()
    yield
    print("🛑 服务关闭,释放数据库连接")
    await async_engine.dispose()  # 关闭异步引擎,释放连接池

app = FastAPI(lifespan=lifespan)

# ==================== 接口示例 ====================
@app.get("/")
async def home():
    return {"msg": "欢迎访问首页"}

# 查询书籍示例接口
@app.get("/books")
async def get_book_list(db: AsyncSession = Depends(get_db)):
    stmt = select(Book)
    result = await db.execute(stmt)
    books = result.scalars().all()
    return [
        {
            "id": item.id,
            "bookname": item.bookname,
            "author": item.author,
            "price": item.price,
            "publisher": item.publisher,
            "create_time": item.create_time,
            "update_time": item.update_time
        }
        for item in books
    ]
相关推荐
benchmark_cc3 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962382434 小时前
python快乐编程网络爬虫课后答案
python·网络爬虫·学习工具·课后答案·刷题app
鹏哥带你干乡墅5 小时前
优选乡墅赋能培训平台如何帮助提升乡村建设?
大数据·人工智能·python
veminhe5 小时前
python调用接口获取网络信息
python
Allen_LVyingbo6 小时前
医疗AI基础2026-构建可靠智能体的编程路径(上)
大数据·数据库·人工智能·python·自动化
Rnan-prince7 小时前
堆与TopK · 从零到通透 —— 9 节全系列复盘
python·算法
2601_962294618 小时前
Python接口自动化测试实战:使用requests库
python·接口自动化测试·异常处理·requests库·api测试
砚底藏山河8 小时前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
阿童木写作8 小时前
跨境电商翻译工具推荐:批量图片翻译+视频字幕实时翻译
人工智能·python·音视频
晶捷软件8 小时前
晶捷智能:集团型制造企业ERP如何实现多工厂统一管控
大数据·人工智能·python·制造