You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI中间件中获取当前路由的Tags

在FastAPI中间件中获取路由Tags并校验Token

要在HTTP中间件里获取当前路由的Tags列表,你可以通过Request对象的route属性拿到对应的APIRoute实例,从中提取Tags信息。具体实现如下:

完整中间件代码

from fastapi import Request, FastAPI, HTTPException

app = FastAPI()

@app.middleware("http")
async def check_auth(request: Request, call_next):
    # 先判断当前请求是否匹配到有效路由
    if request.route:
        # 从APIRoute实例中获取tags列表
        route_tags = request.route.tags
        if 'bearer' in route_tags:
            # 执行Token校验逻辑
            check_token(request)
    
    # 继续处理请求并返回响应
    response = await call_next(request)
    return response

# 你的路由定义
@app.get("/apps", tags=['bearer'])
async def apps():
    return get_apps()

def check_token(request: Request):
    # 编写你的Token校验逻辑
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="无效或缺失的Token")
    # 后续Token验证逻辑...

关键说明

  • request.route:返回当前请求匹配到的APIRoute对象,若请求未匹配任何路由(比如404),该属性为None,因此需要先做存在性判断,避免报错。
  • request.route.tags:直接获取路由定义时设置的tags列表,和你在@app.get装饰器中传入的tags参数完全一致。
  • 优先判断路由是否存在,再处理Tags校验,能避开非路由请求(如静态资源访问)引发的属性不存在问题。

内容的提问来源于stack exchange,提问作者mikeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:32:03