zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    moc处理cpp文件
    程序员!你还能年轻几岁?
    多媒体会议系统中的延迟
    把C++类成员函数集成到lua
    Q_PROPERTY使用
    python与c的集成
    注册C函数与类成员函数到lua
    摄像头(WebCam)在Linux操作系统中的驱动方法
    网络营销实战必读之书推荐:《网络营销实战密码》
    这样写的博客才有更多的人愿意看
  • 原文地址:https://www.cnblogs.com/xiao987334176/p/13130760.html
Copyright © 2011-2022 走看看