from fastapi import APIRouter, Header, HTTPException, Response, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel
routes = APIRouter(tags=["status"])
class Ticket(BaseModel):
title: str
records: dict[int, Ticket] = {1: Ticket(title="start")}
@routes.get("/tickets/{ticket_id}")
def get(ticket_id: int):
if ticket_id < 1:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "invalid ticket id")
if ticket_id not in records:
raise HTTPException(status.HTTP_404_NOT_FOUND, "ticket missing")
return records[ticket_id]
@routes.post("/tickets", status_code=status.HTTP_201_CREATED)
def create(data: Ticket, response: Response):
if any(item.title == data.title for item in records.values()):
raise HTTPException(status.HTTP_409_CONFLICT, "duplicate title")
ticket_id = max(records, default=0) + 1
records[ticket_id] = data
response.headers["Location"] = f"/tickets/{ticket_id}"
return {"id":ticket_id, **data.model_dump()}
@routes.put("/tickets/{ticket_id}", responses={201: {"description":"Created on first write"}})
def put(ticket_id: int, data: Ticket, response: Response):
if ticket_id not in records:
response.status_code = status.HTTP_201_CREATED
records[ticket_id] = data
return data
@routes.delete("/tickets/{ticket_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete(ticket_id: int):
records.pop(ticket_id, None)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@routes.get("/tickets-cache", responses={304: {"description":"Not modified"}})
def cache(if_none_match: str | None = Header(default=None)):
tag = '"tickets-lab"'
if if_none_match == tag:
return Response(status_code=304, headers={"ETag":tag})
return JSONResponse({"dataset":"tickets"}, headers={"ETag":tag})
@routes.get("/tickets-control")
def control(authorization: str | None = Header(default=None)):
if authorization not in ("Bearer view-lab","Bearer write-lab"):
raise HTTPException(401, "authentication required", headers={"WWW-Authenticate":"Bearer"})
if authorization == "Bearer view-lab":
raise HTTPException(403, "write scope required")
return {"allowed":True}
@routes.get("/tickets-failure")
def failure():
raise RuntimeError("synthetic internal failure")
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-response-upload-lab/status_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
status_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a508.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip