register_routes() plugin hook datasette argument, closes #1404

pull/1418/head
Simon Willison 2021-07-26 16:16:46 -07:00
rodzic 6f1731f305
commit eccfeb0871
6 zmienionych plików z 37 dodań i 4 usunięć

Wyświetl plik

@ -960,7 +960,7 @@ class Datasette:
"""Returns an ASGI app function that serves the whole of Datasette"""
routes = []
for routes_to_add in pm.hook.register_routes():
for routes_to_add in pm.hook.register_routes(datasette=self):
for regex, view_fn in routes_to_add:
routes.append((regex, wrap_view(view_fn, self)))

Wyświetl plik

@ -75,7 +75,7 @@ def register_facet_classes():
@hookspec
def register_routes():
def register_routes(datasette):
"""Register URL routes: return a list of (regex, view_function) pairs"""

Wyświetl plik

@ -529,8 +529,11 @@ Examples: `datasette-atom <https://github.com/simonw/datasette-atom>`_, `dataset
.. _plugin_register_routes:
register_routes()
-----------------
register_routes(datasette)
--------------------------
``datasette`` - :ref:`internals_datasette`
You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
Register additional view functions to execute for specified URL routes.

Wyświetl plik

@ -70,6 +70,7 @@ EXPECTED_PLUGINS = [
"extra_template_vars",
"menu_links",
"permission_allowed",
"register_routes",
"render_cell",
"startup",
"table_actions",

Wyświetl plik

@ -1,4 +1,5 @@
from datasette import hookimpl
from datasette.utils.asgi import Response
from functools import wraps
import markupsafe
import json
@ -167,3 +168,12 @@ def table_actions(datasette, database, table, actor, request):
return [{"href": datasette.urls.instance(), "label": label}]
return inner
@hookimpl
def register_routes(datasette):
config = datasette.plugin_config("register-route-demo")
if not config:
return
path = config["path"]
return [(r"/{}/$".format(path), lambda: Response.text(path.upper()))]

Wyświetl plik

@ -648,6 +648,25 @@ def test_hook_register_routes(app_client, path, body):
assert body == response.text
@pytest.mark.parametrize("configured_path", ("path1", "path2"))
def test_hook_register_routes_with_datasette(configured_path):
with make_app_client(
metadata={
"plugins": {
"register-route-demo": {
"path": configured_path,
}
}
}
) as client:
response = client.get(f"/{configured_path}/")
assert response.status == 200
assert configured_path.upper() == response.text
# Other one should 404
other_path = [p for p in ("path1", "path2") if configured_path != p][0]
assert client.get(f"/{other_path}/").status == 404
def test_hook_register_routes_post(app_client):
response = app_client.post("/post/", {"this is": "post data"}, csrftoken_from=True)
assert 200 == response.status