Support request.url_for when only "app" scope is avaialable#2672
Support request.url_for when only "app" scope is avaialable#2672Kludex merged 5 commits intoKludex:masterfrom
request.url_for when only "app" scope is avaialable#2672Conversation
starlette/requests.py
Outdated
| url_pather: Starlette | Router = self.scope.get("app") or self.scope["router"] | ||
| url_path = url_pather.url_path_for(name, **path_params) |
There was a problem hiding this comment.
I needed to fall back to using scope["router"] to support the case where a Router is directly fed to a TestClient, as happens in test_routing.py.
tests/middleware/test_base.py
Outdated
| if request.url == request.url_for("special"): | ||
| return PlainTextResponse("Special") | ||
| return await call_next(request) |
There was a problem hiding this comment.
This shows the main motivation for supporting request.url_for() before call_next: it allows you to handle authentication or other concerns differently depending on the URL without hardcoding paths or path prefixes.
|
Well, actually this is not only for |
70e77e2 to
c80f9be
Compare
@Kludex Let me know if you'd like the commit message changed or anything, that's no problem. Otherwise, it's rebased and ready if you're interested in the change. |
c80f9be to
1387360
Compare
|
As a note, we do the |
request.url_for when only "app" scope is avaialable
|
Thank you! |
Summary
Resolve the bug (or limitation) in this related discussion where
Request.url_for()cannot be called in a middleware inheriting fromBaseHTTPMiddlewarebefore theRouter/call_nextis invoked.Checklist