register_routes() plugin hook (#819)

Fixes #215
This commit is contained in:
Simon Willison 2020-06-08 20:12:06 -07:00 committed by GitHub
commit f5e79adf26
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 129 additions and 4 deletions

View file

@ -46,6 +46,7 @@ EXPECTED_PLUGINS = [
"prepare_connection",
"prepare_jinja2_environment",
"register_facet_classes",
"register_routes",
"render_cell",
],
},

View file

@ -1,6 +1,7 @@
from datasette import hookimpl
from datasette.facets import Facet
from datasette.utils import path_with_added_args
from datasette.utils.asgi import asgi_send_json, Response
import base64
import pint
import json
@ -142,3 +143,27 @@ def permission_allowed(actor, action):
return True
elif action == "this_is_denied":
return False
@hookimpl
def register_routes():
async def one(datasette):
return Response.text(
(await datasette.get_database().execute("select 1 + 1")).first()[0]
)
async def two(request, scope):
name = scope["url_route"]["kwargs"]["name"]
greeting = request.args.get("greeting")
return Response.text("{} {}".format(greeting, name))
async def three(scope, send):
await asgi_send_json(
send, {"hello": "world"}, status=200, headers={"x-three": "1"}
)
return [
(r"/one/$", one),
(r"/two/(?P<name>.*)$", two),
(r"/three/$", three),
]

View file

@ -544,3 +544,18 @@ def test_actor_json(app_client):
assert {"actor": {"id": "bot2", "1+1": 2}} == app_client.get(
"/-/actor.json/?_bot2=1"
).json
@pytest.mark.parametrize(
"path,body", [("/one/", "2"), ("/two/Ray?greeting=Hail", "Hail Ray"),]
)
def test_register_routes(app_client, path, body):
response = app_client.get(path)
assert 200 == response.status
assert body == response.text
def test_register_routes_asgi(app_client):
response = app_client.get("/three/")
assert {"hello": "world"} == response.json
assert "1" == response.headers["x-three"]