蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

记录错误、处理器和请求重定向

PYTHONCPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0error_lab.py
error_lab.py72 行
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException


default=FastAPI()
handled=FastAPI()


@default.get("/locker/{code}")
def locker(code: str):
    if code == "bad":
        raise HTTPException(400, {"code":"BAD_LOCKER", "hint":"use the assigned code"})
    if code == "multiple":
        raise HTTPException(400, ["first", "second"])
    if code == "busy":
        raise HTTPException(429, "please wait", headers={"Retry-After":"3"})
    if code != "A7":
        raise HTTPException(404, "locker missing", headers={"X-Lab-Error":"missing"})
    return {"locker":code}


class ReservationConflict(Exception):
    def __init__(self, slot):
        self.slot=slot


@handled.exception_handler(ReservationConflict)
async def conflict(_request: Request, error: ReservationConflict):
    return JSONResponse({"error":"reservation_conflict","slot":error.slot},status_code=409)


@handled.exception_handler(StarletteHTTPException)
async def http_error(_request: Request, error: StarletteHTTPException):
    return JSONResponse({"error":"http","detail":error.detail},status_code=error.status_code,headers=error.headers)


@handled.exception_handler(RequestValidationError)
async def invalid(_request: Request, error: RequestValidationError):
    issues=[{"loc":list(item["loc"]),"type":item["type"],"msg":item["msg"]} for item in error.errors()]
    return JSONResponse({"error":"validation","issues":issues},status_code=422)


@handled.get("/locker/{number}")
def lookup(number: int):
    if number == 7:
        raise ReservationConflict(number)
    if number == 0:
        raise HTTPException(401,"lab credential required",headers={"WWW-Authenticate":"Bearer"})
    return {"locker":number}


@handled.get("/redirect")
def redirect():
    return RedirectResponse(url="/errors/locker/8")


@handled.post("/redirect-method")
def preserve():
    return RedirectResponse(url="/errors/echo")


@handled.post("/echo")
async def echo(request: Request):
    return {"method":request.method,"received":await request.json()}


@handled.get("/accepted")
def accepted():
    return JSONResponse({"queued":True},status_code=202,headers={"X-Lab-Result":"queued"})
本例需在 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-web-behavior-lab/error_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 error_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:FastAPI

课程关联工程包(登记关联4章) · 含当前章节或实例 · mbskycom202611a512.zip

下载课程关联工程包:FastAPI

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习