Skip to content

Commit

Permalink
Fixed #35354 -- Simplified ASGIRequest path handling.
Browse files Browse the repository at this point in the history
Following the ASGI HTTP Connection Scope docs[0], the provided `path`
is already the correct value that Django requires.

In combination with `root_path`, from which `script_name` is derived,
the `path_info` variable is set. It's then redundant to
re-calculate `path` from `script_name` and `path_info`.

See also, a clarifying discussion on the ASGIref repo[1].

[0]: https://asgi.readthedocs.io/en/latest/specs/www.html#http-connection-scope
[1]: django/asgiref#424
  • Loading branch information
carltongibson committed Apr 5, 2024
1 parent 4d2ef9b commit bcd255c
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 11 deletions.
10 changes: 1 addition & 9 deletions django/core/handlers/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,13 @@ def __init__(self, scope, body_file):
self._post_parse_error = False
self._read_started = False
self.resolver_match = None
self.path = scope["path"]
self.script_name = get_script_prefix(scope)
if self.script_name:
# TODO: Better is-prefix checking, slash handling?
self.path_info = scope["path"].removeprefix(self.script_name)
else:
self.path_info = scope["path"]
# The Django path is different from ASGI scope path args, it should
# combine with script name.
if self.script_name:
self.path = "%s/%s" % (
self.script_name.rstrip("/"),
self.path_info.replace("/", "", 1),
)
else:
self.path = scope["path"]
# HTTP basics.
self.method = self.scope["method"].upper()
# Ensure query string is encoded correctly.
Expand Down
6 changes: 4 additions & 2 deletions tests/handlers/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,13 @@ def test_root_path(self):
self.assertEqual(request.script_name, "/root")
self.assertEqual(request.path_info, "/somepath/")

@override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX/")
@override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX")
def test_force_script_name(self):
async_request_factory = AsyncRequestFactory()
request = async_request_factory.request(**{"path": "/somepath/"})
request = async_request_factory.request(**{"path": "/FORCED_PREFIX/somepath/"})
self.assertEqual(request.path, "/FORCED_PREFIX/somepath/")
self.assertEqual(request.script_name, "/FORCED_PREFIX")
self.assertEqual(request.path_info, "/somepath/")

async def test_sync_streaming(self):
response = await self.async_client.get("/streaming/")
Expand Down

0 comments on commit bcd255c

Please sign in to comment.