Calling "url_for" in a Jinja2 template results in NoMatchFound #2834
-
I am writing a web app in Starlette using Jinja2 templates. While writing a custom token auth system, I stumbled across a NoMatchFound error. So, I tried to figure out why exactly it isn't working. In a lifespan manager, I printed out each route and its associated url_path_for like so: @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)) The following is the output:
So far, so good. I then called url_path_for another time, except directly on the app's router object: print(app.router.url_path_for('token')) This is the resulting stack trace: 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 "". As far as I can tell, I should be getting the appropriate path. Is there something I'm doing wrong here? Or is this an issue with Starlete? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
The name is |
Beta Was this translation helpful? Give feedback.
The name is
'get_token'
, not'token'
.