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

  • 相关阅读:
    【硬件】组装一台多核电脑
    【硬件】组装电脑前的准备工作
    【长知识】设计多核电脑装机方案
    【长知识】认识电脑的硬件组成
    程序员必备基础:如何安全传输存储用户密码?
    二本应届生的大学生活、2020年总结(已上岸百度)
    白日梦的Elasticsearch系列笔记(一)基础篇-- 快手上手ES
    全网最牛X的!!! MySQL两阶段提交串讲
    删库后!除了跑路还能干什么?
    数据库面试简答、30道高频面试题
  • 原文地址:https://www.cnblogs.com/xiao987334176/p/13130760.html
Copyright © 2011-2022 走看看