FastAPI--中间件(6)

发布时间:2020-06-28 10:11:30编辑:admin阅读(2951)

    一、概述

    所谓的中间件,其实和我们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


    1.png

     

     

    总结:

    中间件实际上是一个函数,在每个request处理之前被调用,同时又在每个response返回之前被调用。

    1、首先接收访问过来的request。

    2、然后针对request或其他功能执行自定义逻辑。

    3、传递request给应用程序继续处理。

    4、接收应用所产生的response。

    5、然后针对response或其他功能执行自定义逻辑。

    6、返回response。

     

     

    本文参考链接:

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


关键字