request.url_vars property, closes #822

pull/809/head
Simon Willison 2020-06-08 20:40:00 -07:00
rodzic db660db463
commit fac8e93815
5 zmienionych plików z 28 dodań i 4 usunięć

Wyświetl plik

@ -32,6 +32,10 @@ class Request:
(self.scheme, self.host, self.path, None, self.query_string, None)
)
@property
def url_vars(self):
return (self.scope.get("url_route") or {}).get("kwargs") or {}
@property
def scheme(self):
return self.scope.get("scheme") or "http"

Wyświetl plik

@ -42,6 +42,9 @@ The request object is passed to various plugin hooks. It represents an incoming
``.args`` - MultiParams
An object representing the parsed querystring parameters, see below.
``.url_vars`` - dictionary (str -> str)
Variables extracted from the URL path, if that path was defined using a regular expression. See :ref:`plugin_register_routes`.
``.actor`` - dictionary (str -> Any) or None
The currently authenticated actor (see :ref:`actors <authentication_actor>`), or ``None`` if the request is unauthenticated.

Wyświetl plik

@ -850,8 +850,8 @@ Return a list of ``(regex, async_view_function)`` pairs, something like this:
import html
async def hello_from(scope):
name = scope["url_route"]["kwargs"]["name"]
async def hello_from(request):
name = request.url_vars["name"]
return Response.html("Hello from {}".format(
html.escape(name)
))

Wyświetl plik

@ -152,8 +152,8 @@ def register_routes():
(await datasette.get_database().execute("select 1 + 1")).first()[0]
)
async def two(request, scope):
name = scope["url_route"]["kwargs"]["name"]
async def two(request):
name = request.url_vars["name"]
greeting = request.args.get("greeting")
return Response.text("{} {}".format(greeting, name))

Wyświetl plik

@ -44,3 +44,20 @@ def test_request_args():
assert 2 == len(request.args)
with pytest.raises(KeyError):
request.args["missing"]
def test_request_url_vars():
scope = {
"http_version": "1.1",
"method": "POST",
"path": "/",
"raw_path": b"/",
"query_string": b"",
"scheme": "http",
"type": "http",
"headers": [[b"content-type", b"application/x-www-form-urlencoded"]],
}
assert {} == Request(scope, None).url_vars
assert {"name": "cleo"} == Request(
dict(scope, url_route={"kwargs": {"name": "cleo"}}), None
).url_vars