mirror of
https://github.com/simonw/datasette.git
synced 2025-12-10 16:51:24 +01:00
actors_from_ids plugin hook and datasette.actors_from_ids() method (#2181)
* Prototype of actors_from_ids plugin hook, refs #2180 * datasette-remote-actors example plugin, refs #2180
This commit is contained in:
parent
c26370485a
commit
b645174271
5 changed files with 155 additions and 0 deletions
|
|
@ -1215,3 +1215,65 @@ async def test_hook_register_permissions_allows_identical_duplicates():
|
|||
await ds.invoke_startup()
|
||||
# Check that ds.permissions has only one of each
|
||||
assert len([p for p in ds.permissions.values() if p.abbr == "abbr1"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hook_actors_from_ids():
|
||||
# Without the hook should return default {"id": id} list
|
||||
ds = Datasette()
|
||||
await ds.invoke_startup()
|
||||
db = ds.add_memory_database("actors_from_ids")
|
||||
await db.execute_write(
|
||||
"create table actors (id text primary key, name text, age int)"
|
||||
)
|
||||
await db.execute_write(
|
||||
"insert into actors (id, name, age) values ('3', 'Cate Blanchett', 52)"
|
||||
)
|
||||
await db.execute_write(
|
||||
"insert into actors (id, name, age) values ('5', 'Rooney Mara', 36)"
|
||||
)
|
||||
await db.execute_write(
|
||||
"insert into actors (id, name, age) values ('7', 'Sarah Paulson', 46)"
|
||||
)
|
||||
await db.execute_write(
|
||||
"insert into actors (id, name, age) values ('9', 'Helena Bonham Carter', 55)"
|
||||
)
|
||||
table_names = await db.table_names()
|
||||
assert table_names == ["actors"]
|
||||
actors1 = await ds.actors_from_ids(["3", "5", "7"])
|
||||
assert actors1 == {
|
||||
"3": {"id": "3"},
|
||||
"5": {"id": "5"},
|
||||
"7": {"id": "7"},
|
||||
}
|
||||
|
||||
class ActorsFromIdsPlugin:
|
||||
__name__ = "ActorsFromIdsPlugin"
|
||||
|
||||
@hookimpl
|
||||
def actors_from_ids(self, datasette, actor_ids):
|
||||
db = datasette.get_database("actors_from_ids")
|
||||
|
||||
async def inner():
|
||||
sql = "select id, name from actors where id in ({})".format(
|
||||
", ".join("?" for _ in actor_ids)
|
||||
)
|
||||
actors = {}
|
||||
result = await db.execute(sql, actor_ids)
|
||||
for row in result.rows:
|
||||
actor = dict(row)
|
||||
actors[actor["id"]] = actor
|
||||
return actors
|
||||
|
||||
return inner
|
||||
|
||||
try:
|
||||
pm.register(ActorsFromIdsPlugin(), name="ActorsFromIdsPlugin")
|
||||
actors2 = await ds.actors_from_ids(["3", "5", "7"])
|
||||
assert actors2 == {
|
||||
"3": {"id": "3", "name": "Cate Blanchett"},
|
||||
"5": {"id": "5", "name": "Rooney Mara"},
|
||||
"7": {"id": "7", "name": "Sarah Paulson"},
|
||||
}
|
||||
finally:
|
||||
pm.unregister(name="ReturnNothingPlugin")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue