FastAPI学习-22.response 异常处理 HTTPException

前言

某些情况下,需要向客户端返回错误提示。

这里所谓的客户端包括前端浏览器、其他应用程序、物联网设备等。

需要向客户端返回错误提示的场景主要如下:

  • 客户端没有执行操作的权限
  • 客户端没有访问资源的权限
  • 客户端要访问的项目不存在
  • 等等 ...

遇到这些情况时,通常要返回 4XX (400 至 499)HTTP 状态码
4XX 状态码与表示请求成功的 2XX (200 至 299) HTTP 状态码类似。

只不过,4XX 状态码表示客户端发生的错误。

使用 HTTPException

向客户端返回 HTTP 错误响应,可以使用 HTTPException

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}


@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

触发 HTTPException

HTTPException 是额外包含了和 API 有关数据的常规 Python 异常。

因为是 Python 异常,所以不能 return,只能 raise

如在调用_路径操作函数_里的工具函数时,触发了 HTTPException,FastAPI 就不再继续执行_路径操作函数_中的后续代码,而是立即终止请求,并把 HTTPException 的 HTTP 错误发送至客户端。

在介绍依赖项与安全的章节中,您可以了解更多用 raise 异常代替 return 值的优势。

本例中,客户端用 ID 请求的 item 不存在时,触发状态码为 404 的异常:

python 复制代码
    raise HTTPException(status_code=404, detail="Item not found")

响应结果

请求为 http://example.com/items/fooitem_id「foo」)时,客户端会接收到 HTTP 状态码 - 200 及如下 JSON 响应结果:

python 复制代码
{
  "item": "The Foo Wrestlers"
}

但如果客户端请求 http://example.com/items/baritem_id 「bar」 不存在时),则会接收到 HTTP 状态码 - 404(「未找到」错误)及如下 JSON 响应结果:

python 复制代码
{
  "detail": "Item not found"
}

触发 HTTPException 时,可以用参数 detail 传递任何能转换为 JSON 的值,不仅限于 str

还支持传递 dictlist 等数据结构。
FastAPI 能自动处理这些数据,并将之转换为 JSON。

添加自定义响应头

有些场景下要为 HTTP 错误添加自定义响应头。例如,出于某些方面的安全需要。

一般情况下可能不会需要在代码中直接使用响应头。

但对于某些高级应用场景,还是需要添加自定义响应头:

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}


@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
    if item_id not in items:
        raise HTTPException(
            status_code=404,
            detail="Item not found",
            headers={"X-Error": "There goes my error"},
        )
    return {"item": items[item_id]}

响应结果

python 复制代码
HTTP/1.1 404 Not Found
date: Sun, 24 Sep 2023 01:31:18 GMT
server: uvicorn
x-error: There goes my error
content-length: 27
content-type: application/json

{"detail":"Item not found"}
相关推荐
曲幽12 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽3 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤4 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽4 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily5 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
司徒轩宇5 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi
郝学胜-神的一滴6 天前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi
yaoty7 天前
Python日志存储:从单机同步到分布式异步的7种方案
fastapi·日志·logger