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

posted @   肖祥  阅读(2079)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2018-06-13 python 全栈开发,Day62(外键的变种(三种关系),数据的增删改,单表查询,多表查询)
点击右上角即可分享
微信分享提示