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

Starlette应用中NoMatchFound路由匹配错误求助

Starlette应用中NoMatchFound路由匹配错误求助

我正在用Starlette和Jinja2模板开发一个Web应用,在编写自定义令牌认证系统时遇到了NoMatchFound错误。

为了排查问题,我在生命周期管理器里打印了每个路由及其对应的url_path_for结果,代码如下:

@asynccontextmanager
async def lifespan(app):
    for route in app.router.routes:
        print(route)
        if isinstance(route, Mount):
            if isinstance(route.app, Router):
                for mount_route in route.app.routes:
                    print(mount_route)
                    print(mount_route.url_path_for(mount_route.name))
        else:
            print(route.url_path_for(route.name))

输出结果如下:

Route(path='/', name='index', methods=['GET', 'HEAD'])
/
Route(path='/login', name='login', methods=['GET', 'HEAD'])
/login
Route(path='/logout', name='logout', methods=['GET', 'HEAD'])
/logout
Route(path='/token', name='get_token', methods=['POST'])
/token
Mount(path='/admin', name='', app=<starlette.routing.Router object at 0x000002CB2403E520>)
Mount(path='/user', name='', app=<starlette.routing.Router object at 0x000002CB24138640>)
Mount(path='/static', name='static', app=<starlette.staticfiles.StaticFiles object at 0x000002CB240396A0>)

看起来一切正常,但当我直接在应用的router对象上调用url_path_for时:

print(app.router.url_path_for('token'))

却得到了如下错误栈:

ERROR:    Traceback (most recent call last):
  File ".venv\Lib\site-packages\starlette\routing.py", line 693, in lifespan
    async with self.lifespan_context(app) as maybe_state:
               ~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "Python\Python313\Lib\contextlib.py", line 214, in __aenter__
    return await anext(self.gen)
           ^^^^^^^^^^^^^^^^^^^^^
  File "<project root>\main\webapp\main.py", line 30, in lifespan
    print(app.router.url_path_for('token'))
          ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
  File ".venv\Lib\site-packages\starlette\routing.py", line 662, in url_path_for
    raise NoMatchFound(name, path_params)
starlette.routing.NoMatchFound: No route exists for name "token" and params "".

我试过把参数换成"/token",还是得到同样的错误。

就我观察来看,我应该能获取到对应的路径才对,是我哪里操作错了吗?还是Starlette本身的问题?

备注:内容来源于stack exchange,提问作者EntangledLabs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 03:18:19