request.full_path property, closes #1184

This commit is contained in:
Simon Willison 2021-01-11 13:32:58 -08:00
commit 649f48cd70
3 changed files with 38 additions and 5 deletions

View file

@ -89,6 +89,14 @@ class Request:
def query_string(self): def query_string(self):
return (self.scope.get("query_string") or b"").decode("latin-1") return (self.scope.get("query_string") or b"").decode("latin-1")
@property
def full_path(self):
qs = self.query_string
return "{}{}".format(
self.path,
('?' + qs) if qs else ''
)
@property @property
def args(self): def args(self):
return MultiParams(parse_qs(qs=self.query_string)) return MultiParams(parse_qs(qs=self.query_string))

View file

@ -35,7 +35,10 @@ The request object is passed to various plugin hooks. It represents an incoming
The host header from the incoming request, e.g. ``latest.datasette.io`` or ``localhost``. The host header from the incoming request, e.g. ``latest.datasette.io`` or ``localhost``.
``.path`` - string ``.path`` - string
The path of the request, e.g. ``/fixtures``. The path of the request excluding the query string, e.g. ``/fixtures``.
``.full_path`` - string
The path of the request including the query string if one is present, e.g. ``/fixtures?sql=select+sqlite_version()``.
``.query_string`` - string ``.query_string`` - string
The query string component of the request, without the ``?`` - e.g. ``name__contains=sam&age__gt=10``. The query string component of the request, without the ``?`` - e.g. ``name__contains=sam&age__gt=10``.

View file

@ -90,3 +90,25 @@ def test_request_url_vars():
assert {"name": "cleo"} == Request( assert {"name": "cleo"} == Request(
dict(scope, url_route={"kwargs": {"name": "cleo"}}), None dict(scope, url_route={"kwargs": {"name": "cleo"}}), None
).url_vars ).url_vars
@pytest.mark.parametrize("path,query_string,expected_full_path", [
("/", "", "/"),
("/", "foo=bar", "/?foo=bar"),
("/foo", "bar", "/foo?bar")
])
def test_request_properties(path, query_string, expected_full_path):
scope = {
"http_version": "1.1",
"method": "POST",
"path": path,
"raw_path": path.encode("latin-1"),
"query_string": query_string.encode("latin-1"),
"scheme": "http",
"type": "http",
}
request = Request(scope, None)
assert request.path == path
assert request.query_string == query_string
assert request.full_path == expected_full_path