INFO: Started server process [12136]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO:127.0.0.1:3229-"GET /items/foo HTTP/1.1"200 OK
INFO:127.0.0.1:3240-"GET /items/bar HTTP/1.1"404 Not Found
HTTPException(status_code=404, detail={"msg":"item not found!","name":["michael","ming"]})
5. 自定義響應頭
HTTPException(headers=xxx)
@app.get("/items-header/{item_id}")asyncdefread_item_header(item_id:str):if item_id notin items:raise HTTPException(status_code=404,detail="Item not found",headers={"X-Error":"There goes my error!!!"},)return{"item": items[item_id]}
6. 自定義異常處理器
自定義異常類
編寫 handler @app.exception_handler(要處理的異常類)
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponseclassMichaelException(Exception):def__init__(self, name:str):self.name = nameapp = FastAPI()@app.exception_handler(MichaelException)asyncdefmichael_exception_handler(request: Request,exec: MichaelException):return JSONResponse(status_code=408,content ={"msg":"哦,{}出錯了".format(exec.name)})@app.get("/test/{name}")asyncdeftest(name:str):if name =="yoyo":raise MichaelException(name)return{"test_name": name}
7. 覆蓋默認異常處理器
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponseapp = FastAPI()@app.get("/items/{item_id}")asyncdefread_item(item_id:int):if item_id ==3:raise HTTPException(status_code=418, detail="3 is not a good number")return{"item_id": item_id}
更改 RequestValidationError 錯誤的處理 handler
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponseapp = FastAPI()@app.exception_handler(RequestValidationError)asyncdefvalid_excep_handler(req,exec):return PlainTextResponse(str(exec), status_code=400)@app.get("/items/{item_id}")asyncdefread_item(item_id:int):if item_id ==3:raise HTTPException(status_code=418, detail="3 is not a good number")return{"item_id": item_id}
同樣的,處理 HTTPException 的 handler,自定義處理
from starlette.exceptions import HTTPException as StarletteHTTPException
# 跟 fastapi 的 HTTPException 一樣@app.exception_handler(StarletteHTTPException)asyncdefhttp_exception_handler(req, exc):return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.post("/items/", response_model=Item, tags=["items, ming"], status_code=201,summary="創(chuàng)建item",)asyncdefcreate_item(item: Item):'''多行注釋 --> description- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item'''return item
10.3 response description
response_description 參數(shù)
@app.post("/items/", response_model=Item, tags=["items, ming"], status_code=201,summary="創(chuàng)建item",response_description="響應的描述")asyncdefcreate_item(item: Item):'''多行注釋 --> description,支持 MD 格式## 1. 標題- **name**: each item must have a name- **description**: a long description- **price**: required- **tax**: if the item doesn't have tax, you can omit this- **tags**: a set of unique tag strings for this item'''return item