FastAPI--中間件(6)


一、概述

所謂的中間件,其實和我們bottle中的中間件作用是一致。有些方法或操作需要在所有路由之前執行,比如要加一個http訪問的攔截器,可以對部分接口API需要授權才能訪問的接口進行驗證之類的。

FastAPI提供了一個@app.middleware("http")可以做到類似上面的攔截功能。其實和bottle或flask 鈎子函數很相似

 

二、示例

示例如下:

import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

import time
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

app = FastAPI()


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse({'mes': '觸發了RequestValidationError錯誤,,錯誤信息:%s 你妹的錯了!' % (str(exc))})


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

然后我們請求完成后發現,我們的響應頭里多了一個新增的請求頭:

 

http://127.0.0.1:8000/items/2

 

 

總結:

中間件實際上是一個函數,在每個request處理之前被調用,同時又在每個response返回之前被調用。

1、首先接收訪問過來的request。

2、然后針對request或其他功能執行自定義邏輯。

3、傳遞request給應用程序繼續處理。

4、接收應用所產生的response。

5、然后針對response或其他功能執行自定義邏輯。

6、返回response。

 

 

本文參考鏈接:

http://www.zyiz.net/tech/detail-119883.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM