Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed URLRouter root_path handling. #1954

Merged
merged 2 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions channels/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ async def __call__(self, scope, receive, send):
path = scope.get("path_remaining", scope.get("path", None))
if path is None:
raise ValueError("No 'path' key in connection scope, cannot route URLs")

if "path_remaining" not in scope:
# We are the outermost URLRouter, so handle root_path if present.
root_path = scope.get("root_path", "")
if root_path and not path.startswith(root_path):
# If root_path is present, path must start with it.
raise ValueError("No route found for path %r." % path)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably mention root_path as well, but I was not sure how best to phrase it. Suggestions welcome.

path = path[len(root_path) :]

# Remove leading / to match Django's handling
path = path.lstrip("/")
# Run through the routes we have until one matches
Expand Down
40 changes: 40 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,23 @@ async def test_url_router():
"args": tuple(),
"kwargs": {"default": 42},
}
# Valid root_path in scope
assert (
await router(
{"type": "http", "path": "/root/", "root_path": "/root"}, None, None
)
== 1
)
assert (
await router(
{"type": "http", "path": "/root/foo/", "root_path": "/root"}, None, None
)
== 2
)

# Unmatched root_path in scope
with pytest.raises(ValueError):
await router({"type": "http", "path": "/", "root_path": "/root"}, None, None)

# Invalid matches
with pytest.raises(ValueError):
Expand Down Expand Up @@ -261,6 +278,29 @@ async def test_path_remaining():
== 2
)

assert (
await outermost_router(
{"type": "http", "path": "/root/prefix/stuff/", "root_path": "/root"},
None,
None,
)
== 2
)

with pytest.raises(ValueError):
await outermost_router(
{"type": "http", "path": "/root/root/prefix/stuff/", "root_path": "/root"},
None,
None,
)

with pytest.raises(ValueError):
await outermost_router(
{"type": "http", "path": "/root/prefix/root/stuff/", "root_path": "/root"},
None,
None,
)


def test_invalid_routes():
"""
Expand Down