-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from paulcwatts/relative-urls
Fix absolute/relative URLs
- Loading branch information
Showing
5 changed files
with
63 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
"""Utilities for constructing relative URLs.""" | ||
|
||
from typing import TYPE_CHECKING, Any | ||
|
||
from starlette.requests import Request | ||
|
||
if TYPE_CHECKING: | ||
from starlette.applications import Starlette # pragma: nocover | ||
from starlette.routing import Router # pragma: nocover | ||
|
||
|
||
def rel_url_for(req: Request, name: str, /, **path_params: Any) -> str: | ||
"""Provide a relative URL for a path.""" | ||
url_path_provider: Router | Starlette | None = req.scope.get( | ||
"router" | ||
) or req.scope.get("app") | ||
if url_path_provider is None: | ||
msg = "`rel_url_for` method can only be used inside a Starlette application." | ||
raise RuntimeError(msg) | ||
return url_path_provider.url_path_for(name, **path_params) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import pytest | ||
from starlette.requests import Request | ||
|
||
from saml_idp.urls import rel_url_for | ||
|
||
|
||
def test_rel_url_for_error() -> None: | ||
"""Throw an error when there's no router.""" | ||
req = Request({"type": "http"}) | ||
with pytest.raises(RuntimeError, match=r"can only be used"): | ||
rel_url_for(req, "login") |