Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
6_handle_error.py 3.11 KB
Copy Edit Raw Blame History
尹煜 authored 2023-06-03 21:10 . 6章内容
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
'''
1.2 使用 HTTPException
'''
items = {"yinyu": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")#触发 HTTPException 时,可以用参数 detail 传递任何能转换为 JSON 的值,不仅限于 str。还支持传递 dict、list 等数据结构。
return {"item": items[item_id]}
'''
2.1 自定义响应头
'''
@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]}
'''
2.2 自定义异常处理器
'''
class SelfDefinedException(Exception):
def __init__(self, name: str):
self.name = name
@app.exception_handler(SelfDefinedException)
async def defined_exception_handler(request: Request, exc: SelfDefinedException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/self_defined/{name}")
async def read_defined(name: str):
if name == "yolo":
raise SelfDefinedException(name=name)
return {"unicorn_name": name}
'''
2.3 覆盖默认异常处理器
'''
'''覆盖请求验证异常'''
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse("RequestValidation:"+str(exc), status_code=400)
@app.get("/items2/{item_id}")
async def read_item(item_id: int):
if item_id == 3:
raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
return {"item_id": item_id}
'''覆盖 HTTPException 错误处理器'''
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.get("/items3/{item_id}")
async def read_item(item_id: int):
if item_id == 3:
raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
return {"item_id": item_id}
''' 使用 RequestValidationError 的请求体'''
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
)
class Item(BaseModel):
title: str
size: int
@app.post("/items4/")
async def create_item(item: Item):
return item
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化