蓝色天空网mbsky.com · 知识 · 实践 · 创造FastAPI · 本地阅读预览
教程 / Python / 数据科学 / FastAPI

FastAPI 与 SQLAlchemy 数据库

在临时 SQLite 库观察请求会话、数据模型、外键、口令散列和事务回滚。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

数据库连接与请求会话

把引擎和会话工厂放在 database.py。SQLite 使用文件地址 sqlite:///./sql_app.db 时,相对路径以启动目录为准。本站实验用临时目录,避免污染项目数据。需要连接 PostgreSQL 或 MySQL 时,URL 还要指定对应驱动与服务,密钥应从运行配置传入。

SQLAlchemy 2.x 用 create_engine 建立引擎,sessionmaker 建立会话工厂,DeclarativeBase 定义 ORM 基类。每次请求使用新的 Session。FastAPI 的 yield 依赖提供会话,finally 无论成功或失败都关闭。SQLite 的 check_same_thread=False 允许驱动连接跨线程使用,会话仍需由单个工作单元独占。

本工程保留 autoflush=False。关闭的是查询前的自动刷新,commit 仍会刷新待写变更。提交失败后 rollback,再继续使用该会话。建表演示使用 create_all,已有库的表结构演进需要明确迁移。

把持久化对象与请求响应分开

db_models.py 声明 Account 与 Note。Mapped 和 mapped_column 描述主键、唯一邮箱、密码散列与外键,relationship 描述账号和多条笔记的关联。本站逐连接启用 SQLite 外键约束,直接写入缺失账号的笔记会失败。

db_schemas.py 分开创建输入和公开响应。Pydantic v2 的 ConfigDict(from_attributes=True) 可从 ORM 对象属性读取字段,替代旧写法 orm_mode。创建输入含口令,公开响应只含编号、邮箱与状态。本站以独立 SQLite 查询核对磁盘存储 Argon2id 散列。

CRUD 与事务的可观察结果

db_crud.py 封装查询和写入,db_routes.py 将数据库结果转换为 HTTP 契约。创建账号先散列口令再写库,邮箱冲突返回 409。按 ID 读取缺失账号返回 404,列表按编号排序再应用 offset 和 limit。

创建笔记先检查所属账号,并由数据库外键保护引用完整性。PUT 替换标题后再从列表读取,DELETE 返回 204,之后列表应为空。故意触发一次外键错误,回滚后在同一会话再次查询账号,以确认连接可继续使用。

数据库示例使用虚构资料并独立于前一章的认证账号。这里验证的是存储关系,真实业务还需将写入和读取权限绑定到经过认证的用户。

数据库 URL 的组成

数据库连接方式与本机范围
SQLitesqlite:///./sql_app.db 指向相对路径,实验另用临时文件。
PostgreSQLpostgresql://user:password@localhost/dbname 表示连接服务,可显式选 postgresql+psycopg 并安装 psycopg。
MySQLmysql+pymysql://user:password@localhost/dbname 指定 PyMySQL 驱动和 MySQL 服务。

用 SQLite 保存账号及其笔记

python · 阅读源码
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session

from database import get_db
from db_crud import accounts, add_account, add_note, by_email, notes
from db_models import Account, Note
from db_schemas import AccountOut, NewAccount, NewNote, NoteOut


routes=APIRouter(prefix="/db",tags=["database"])
DB=Annotated[Session,Depends(get_db)]
Offset=Annotated[int,Query(ge=0)]
Limit=Annotated[int,Query(ge=1,le=100)]


@routes.post("/accounts",response_model=AccountOut,status_code=201,operation_id="db_add_account")
def create_account(data:NewAccount,db:DB):
    if by_email(db,data.email):
        raise HTTPException(409,"email already registered")
    try:
        return add_account(db,data)
    except IntegrityError as error:
        db.rollback()
        # This route inserts a generated ID and a validated payload. The email constraint can race.
        if by_email(db,data.email):
            raise HTTPException(409,"email already registered") from error
        raise


@routes.get("/accounts",response_model=list[AccountOut])
def list_accounts(db:DB,offset:Offset=0,limit:Limit=10):
    return accounts(db,offset,limit)


@routes.get("/accounts/{account_id}",response_model=AccountOut)
def read_account(account_id:int,db:DB):
    account=db.get(Account,account_id)
    if account is None:
        raise HTTPException(404,"account missing")
    return account


@routes.post("/accounts/{account_id}/notes",response_model=NoteOut,status_code=201)
def create_note(account_id:int,data:NewNote,db:DB):
    owner=db.get(Account,account_id)
    if owner is None:
        raise HTTPException(404,"account missing")
    return add_note(db,owner,data)


@routes.get("/notes",response_model=list[NoteOut])
def list_notes(db:DB,offset:Offset=0,limit:Limit=10):
    return notes(db,offset,limit)


def note_or_404(note_id,db):
    note=db.get(Note,note_id)
    if note is None:
        raise HTTPException(404,"note missing")
    return note


@routes.put("/notes/{note_id}",response_model=NoteOut)
def update_note(note_id:int,data:NewNote,db:DB):
    note=note_or_404(note_id,db)
    note.title=data.title
    db.commit()
    db.refresh(note)
    return note


@routes.delete("/notes/{note_id}",status_code=204)
def delete_note(note_id:int,db:DB):
    db.delete(note_or_404(note_id,db))
    db.commit()
    return Response(status_code=204)
预期结果 · 待实际运行核验
  • 账号响应只展示公开字段。笔记可增改删,缺失账号被拒绝,数据库外键错误回滚后仍可查询。
用 SQLite 保存账号及其笔记

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

当前源码 SHA256:5f092457b6accf6288c52a214fedbfd0e24b384c8abaee4260a8531969ffd348

下载本站示例源码

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本站 FastAPI 实验工程

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

ZIP SHA256:8c080602eaa57efb9303a20e21b1f2e3a50e60b5f38a6c4cac8321523072b3fa

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

创建同一邮箱两次,再分别给存在与不存在的账号创建笔记。

展开参考解答

首次创建返回 201,重复邮箱为 409。笔记在已有账号下创建成功,缺失账号返回 404。

规范与官方依据