Debian Codegraph @

docs/plugin_hooks.rst

raw
1 .. _plugin_hooks:
2
3 Plugin hooks
4 ============
5
6 Datasette :ref:`plugins <plugins>` use *plugin hooks* to customize Datasette's behavior. These hooks are powered by the `pluggy <https://pluggy.readthedocs.io/>`__ plugin system.
7
8 Each plugin can implement one or more hooks using the ``@hookimpl`` decorator against a function named that matches one of the hooks documented on this page.
9
10 When you implement a plugin hook you can accept any or all of the parameters that are documented as being passed to that hook.
11
12 For example, you can implement the ``render_cell`` plugin hook like this even though the full documented hook signature is ``render_cell(row, value, column, table, database, datasette)``:
13
14 .. code-block:: python
15
16 @hookimpl
17 def render_cell(value, column):
18 if column == "stars":
19 return "*" * int(value)
20
21 .. contents:: List of plugin hooks
22 :local:
23 :class: this-will-duplicate-information-and-it-is-still-useful-here
24
25 .. _plugin_hook_prepare_connection:
26
27 prepare_connection(conn, database, datasette)
28 ---------------------------------------------
29
30 ``conn`` - sqlite3 connection object
31 The connection that is being opened
32
33 ``database`` - string
34 The name of the database
35
36 ``datasette`` - :ref:`internals_datasette`
37 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
38
39 This hook is called when a new SQLite database connection is created. You can
40 use it to `register custom SQL functions <https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.create_function>`_,
41 aggregates and collations. For example:
42
43 .. code-block:: python
44
45 from datasette import hookimpl
46 import random
47
48
49 @hookimpl
50 def prepare_connection(conn):
51 conn.create_function(
52 "random_integer", 2, random.randint
53 )
54
55 This registers a SQL function called ``random_integer`` which takes two
56 arguments and can be called like this::
57
58 select random_integer(1, 10);
59
60 Examples: `datasette-jellyfish <https://datasette.io/plugins/datasette-jellyfish>`__, `datasette-jq <https://datasette.io/plugins/datasette-jq>`__, `datasette-haversine <https://datasette.io/plugins/datasette-haversine>`__, `datasette-rure <https://datasette.io/plugins/datasette-rure>`__
61
62 .. _plugin_hook_prepare_jinja2_environment:
63
64 prepare_jinja2_environment(env, datasette)
65 ------------------------------------------
66
67 ``env`` - jinja2 Environment
68 The template environment that is being prepared
69
70 ``datasette`` - :ref:`internals_datasette`
71 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
72
73 This hook is called with the Jinja2 environment that is used to evaluate
74 Datasette HTML templates. You can use it to do things like `register custom
75 template filters <http://jinja.pocoo.org/docs/2.10/api/#custom-filters>`_, for
76 example:
77
78 .. code-block:: python
79
80 from datasette import hookimpl
81
82
83 @hookimpl
84 def prepare_jinja2_environment(env):
85 env.filters["uppercase"] = lambda u: u.upper()
86
87 You can now use this filter in your custom templates like so::
88
89 Table name: {{ table|uppercase }}
90
91 This function can return an awaitable function if it needs to run any async code.
92
93 Examples: `datasette-edit-templates <https://datasette.io/plugins/datasette-edit-templates>`_
94
95 .. _plugin_hook_extra_template_vars:
96
97 extra_template_vars(template, database, table, columns, view_name, request, datasette)
98 --------------------------------------------------------------------------------------
99
100 Extra template variables that should be made available in the rendered template context.
101
102 ``template`` - string
103 The template that is being rendered, e.g. ``database.html``
104
105 ``database`` - string or None
106 The name of the database, or ``None`` if the page does not correspond to a database (e.g. the root page)
107
108 ``table`` - string or None
109 The name of the table, or ``None`` if the page does not correct to a table
110
111 ``columns`` - list of strings or None
112 The names of the database columns that will be displayed on this page. ``None`` if the page does not contain a table.
113
114 ``view_name`` - string
115 The name of the view being displayed. (``index``, ``database``, ``table``, and ``row`` are the most important ones.)
116
117 ``request`` - :ref:`internals_request` or None
118 The current HTTP request. This can be ``None`` if the request object is not available.
119
120 ``datasette`` - :ref:`internals_datasette`
121 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
122
123 This hook can return one of three different types:
124
125 Dictionary
126 If you return a dictionary its keys and values will be merged into the template context.
127
128 Function that returns a dictionary
129 If you return a function it will be executed. If it returns a dictionary those values will will be merged into the template context.
130
131 Function that returns an awaitable function that returns a dictionary
132 You can also return a function which returns an awaitable function which returns a dictionary.
133
134 Datasette runs Jinja2 in `async mode <https://jinja.palletsprojects.com/en/2.10.x/api/#async-support>`__, which means you can add awaitable functions to the template scope and they will be automatically awaited when they are rendered by the template.
135
136 Here's an example plugin that adds a ``"user_agent"`` variable to the template context containing the current request's User-Agent header:
137
138 .. code-block:: python
139
140 @hookimpl
141 def extra_template_vars(request):
142 return {"user_agent": request.headers.get("user-agent")}
143
144 This example returns an awaitable function which adds a list of ``hidden_table_names`` to the context:
145
146 .. code-block:: python
147
148 @hookimpl
149 def extra_template_vars(datasette, database):
150 async def hidden_table_names():
151 if database:
152 db = datasette.databases[database]
153 return {
154 "hidden_table_names": await db.hidden_table_names()
155 }
156 else:
157 return {}
158
159 return hidden_table_names
160
161 And here's an example which adds a ``sql_first(sql_query)`` function which executes a SQL statement and returns the first column of the first row of results:
162
163 .. code-block:: python
164
165 @hookimpl
166 def extra_template_vars(datasette, database):
167 async def sql_first(sql, dbname=None):
168 dbname = (
169 dbname
170 or database
171 or next(iter(datasette.databases.keys()))
172 )
173 result = await datasette.execute(dbname, sql)
174 return result.rows[0][0]
175
176 return {"sql_first": sql_first}
177
178 You can then use the new function in a template like so::
179
180 SQLite version: {{ sql_first("select sqlite_version()") }}
181
182 Examples: `datasette-search-all <https://datasette.io/plugins/datasette-search-all>`_, `datasette-template-sql <https://datasette.io/plugins/datasette-template-sql>`_
183
184 .. _plugin_hook_extra_css_urls:
185
186 extra_css_urls(template, database, table, columns, view_name, request, datasette)
187 ---------------------------------------------------------------------------------
188
189 This takes the same arguments as :ref:`extra_template_vars(...) <plugin_hook_extra_template_vars>`
190
191 Return a list of extra CSS URLs that should be included on the page. These can
192 take advantage of the CSS class hooks described in :ref:`customization`.
193
194 This can be a list of URLs:
195
196 .. code-block:: python
197
198 from datasette import hookimpl
199
200
201 @hookimpl
202 def extra_css_urls():
203 return [
204 "https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
205 ]
206
207 Or a list of dictionaries defining both a URL and an
208 `SRI hash <https://www.srihash.org/>`_:
209
210 .. code-block:: python
211
212 @hookimpl
213 def extra_css_urls():
214 return [
215 {
216 "url": "https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css",
217 "sri": "sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4",
218 }
219 ]
220
221 This function can also return an awaitable function, useful if it needs to run any async code:
222
223 .. code-block:: python
224
225 @hookimpl
226 def extra_css_urls(datasette):
227 async def inner():
228 db = datasette.get_database()
229 results = await db.execute(
230 "select url from css_files"
231 )
232 return [r[0] for r in results]
233
234 return inner
235
236 Examples: `datasette-cluster-map <https://datasette.io/plugins/datasette-cluster-map>`_, `datasette-vega <https://datasette.io/plugins/datasette-vega>`_
237
238 .. _plugin_hook_extra_js_urls:
239
240 extra_js_urls(template, database, table, columns, view_name, request, datasette)
241 --------------------------------------------------------------------------------
242
243 This takes the same arguments as :ref:`extra_template_vars(...) <plugin_hook_extra_template_vars>`
244
245 This works in the same way as ``extra_css_urls()`` but for JavaScript. You can
246 return a list of URLs, a list of dictionaries or an awaitable function that returns those things:
247
248 .. code-block:: python
249
250 from datasette import hookimpl
251
252
253 @hookimpl
254 def extra_js_urls():
255 return [
256 {
257 "url": "https://code.jquery.com/jquery-3.3.1.slim.min.js",
258 "sri": "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo",
259 }
260 ]
261
262 You can also return URLs to files from your plugin's ``static/`` directory, if
263 you have one:
264
265 .. code-block:: python
266
267 @hookimpl
268 def extra_js_urls():
269 return ["/-/static-plugins/your-plugin/app.js"]
270
271 Note that ``your-plugin`` here should be the hyphenated plugin name - the name that is displayed in the list on the ``/-/plugins`` debug page.
272
273 If your code uses `JavaScript modules <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules>`__ you should include the ``"module": True`` key. See :ref:`customization_css_and_javascript` for more details.
274
275 .. code-block:: python
276
277 @hookimpl
278 def extra_js_urls():
279 return [
280 {
281 "url": "/-/static-plugins/your-plugin/app.js",
282 "module": True,
283 }
284 ]
285
286 Examples: `datasette-cluster-map <https://datasette.io/plugins/datasette-cluster-map>`_, `datasette-vega <https://datasette.io/plugins/datasette-vega>`_
287
288 .. _plugin_hook_extra_body_script:
289
290 extra_body_script(template, database, table, columns, view_name, request, datasette)
291 ------------------------------------------------------------------------------------
292
293 Extra JavaScript to be added to a ``<script>`` block at the end of the ``<body>`` element on the page.
294
295 This takes the same arguments as :ref:`extra_template_vars(...) <plugin_hook_extra_template_vars>`
296
297 The ``template``, ``database``, ``table`` and ``view_name`` options can be used to return different code depending on which template is being rendered and which database or table are being processed.
298
299 The ``datasette`` instance is provided primarily so that you can consult any plugin configuration options that may have been set, using the ``datasette.plugin_config(plugin_name)`` method documented above.
300
301 This function can return a string containing JavaScript, or a dictionary as described below, or a function or awaitable function that returns a string or dictionary.
302
303 Use a dictionary if you want to specify that the code should be placed in a ``<script type="module">...</script>`` element:
304
305 .. code-block:: python
306
307 @hookimpl
308 def extra_body_script():
309 return {
310 "module": True,
311 "script": "console.log('Your JavaScript goes here...')",
312 }
313
314 This will add the following to the end of your page:
315
316 .. code-block:: html
317
318 <script type="module">console.log('Your JavaScript goes here...')</script>
319
320 Example: `datasette-cluster-map <https://datasette.io/plugins/datasette-cluster-map>`_
321
322 .. _plugin_hook_publish_subcommand:
323
324 publish_subcommand(publish)
325 ---------------------------
326
327 ``publish`` - Click publish command group
328 The Click command group for the ``datasette publish`` subcommand
329
330 This hook allows you to create new providers for the ``datasette publish``
331 command. Datasette uses this hook internally to implement the default ``cloudrun``
332 and ``heroku`` subcommands, so you can read
333 `their source <https://github.com/simonw/datasette/tree/main/datasette/publish>`_
334 to see examples of this hook in action.
335
336 Let's say you want to build a plugin that adds a ``datasette publish my_hosting_provider --api_key=xxx mydatabase.db`` publish command. Your implementation would start like this:
337
338 .. code-block:: python
339
340 from datasette import hookimpl
341 from datasette.publish.common import (
342 add_common_publish_arguments_and_options,
343 )
344 import click
345
346
347 @hookimpl
348 def publish_subcommand(publish):
349 @publish.command()
350 @add_common_publish_arguments_and_options
351 @click.option(
352 "-k",
353 "--api_key",
354 help="API key for talking to my hosting provider",
355 )
356 def my_hosting_provider(
357 files,
358 metadata,
359 extra_options,
360 branch,
361 template_dir,
362 plugins_dir,
363 static,
364 install,
365 plugin_secret,
366 version_note,
367 secret,
368 title,
369 license,
370 license_url,
371 source,
372 source_url,
373 about,
374 about_url,
375 api_key,
376 ): ...
377
378 Examples: `datasette-publish-fly <https://datasette.io/plugins/datasette-publish-fly>`_, `datasette-publish-vercel <https://datasette.io/plugins/datasette-publish-vercel>`_
379
380 .. _plugin_hook_render_cell:
381
382 render_cell(row, value, column, table, database, datasette)
383 -----------------------------------------------------------
384
385 Lets you customize the display of values within table cells in the HTML table view.
386
387 ``row`` - ``sqlite.Row``
388 The SQLite row object that the value being rendered is part of
389
390 ``value`` - string, integer, float, bytes or None
391 The value that was loaded from the database
392
393 ``column`` - string
394 The name of the column being rendered
395
396 ``table`` - string or None
397 The name of the table - or ``None`` if this is a custom SQL query
398
399 ``database`` - string
400 The name of the database
401
402 ``datasette`` - :ref:`internals_datasette`
403 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
404
405 If your hook returns ``None``, it will be ignored. Use this to indicate that your hook is not able to custom render this particular value.
406
407 If the hook returns a string, that string will be rendered in the table cell.
408
409 If you want to return HTML markup you can do so by returning a ``jinja2.Markup`` object.
410
411 You can also return an awaitable function which returns a value.
412
413 Datasette will loop through all available ``render_cell`` hooks and display the value returned by the first one that does not return ``None``.
414
415 Here is an example of a custom ``render_cell()`` plugin which looks for values that are a JSON string matching the following format::
416
417 {"href": "https://www.example.com/", "label": "Name"}
418
419 If the value matches that pattern, the plugin returns an HTML link element:
420
421 .. code-block:: python
422
423 from datasette import hookimpl
424 import markupsafe
425 import json
426
427
428 @hookimpl
429 def render_cell(value):
430 # Render {"href": "...", "label": "..."} as link
431 if not isinstance(value, str):
432 return None
433 stripped = value.strip()
434 if not (
435 stripped.startswith("{") and stripped.endswith("}")
436 ):
437 return None
438 try:
439 data = json.loads(value)
440 except ValueError:
441 return None
442 if not isinstance(data, dict):
443 return None
444 if set(data.keys()) != {"href", "label"}:
445 return None
446 href = data["href"]
447 if not (
448 href.startswith("/")
449 or href.startswith("http://")
450 or href.startswith("https://")
451 ):
452 return None
453 return markupsafe.Markup(
454 '<a href="{href}">{label}</a>'.format(
455 href=markupsafe.escape(data["href"]),
456 label=markupsafe.escape(data["label"] or "")
457 or "&nbsp;",
458 )
459 )
460
461 Examples: `datasette-render-binary <https://datasette.io/plugins/datasette-render-binary>`_, `datasette-render-markdown <https://datasette.io/plugins/datasette-render-markdown>`__, `datasette-json-html <https://datasette.io/plugins/datasette-json-html>`__
462
463 .. _plugin_register_output_renderer:
464
465 register_output_renderer(datasette)
466 -----------------------------------
467
468 ``datasette`` - :ref:`internals_datasette`
469 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
470
471 Registers a new output renderer, to output data in a custom format. The hook function should return a dictionary, or a list of dictionaries, of the following shape:
472
473 .. code-block:: python
474
475 @hookimpl
476 def register_output_renderer(datasette):
477 return {
478 "extension": "test",
479 "render": render_demo,
480 "can_render": can_render_demo, # Optional
481 }
482
483 This will register ``render_demo`` to be called when paths with the extension ``.test`` (for example ``/database.test``, ``/database/table.test``, or ``/database/table/row.test``) are requested.
484
485 ``render_demo`` is a Python function. It can be a regular function or an ``async def render_demo()`` awaitable function, depending on if it needs to make any asynchronous calls.
486
487 ``can_render_demo`` is a Python function (or ``async def`` function) which accepts the same arguments as ``render_demo`` but just returns ``True`` or ``False``. It lets Datasette know if the current SQL query can be represented by the plugin - and hence influence if a link to this output format is displayed in the user interface. If you omit the ``"can_render"`` key from the dictionary every query will be treated as being supported by the plugin.
488
489 When a request is received, the ``"render"`` callback function is called with zero or more of the following arguments. Datasette will inspect your callback function and pass arguments that match its function signature.
490
491 ``datasette`` - :ref:`internals_datasette`
492 For accessing plugin configuration and executing queries.
493
494 ``columns`` - list of strings
495 The names of the columns returned by this query.
496
497 ``rows`` - list of ``sqlite3.Row`` objects
498 The rows returned by the query.
499
500 ``sql`` - string
501 The SQL query that was executed.
502
503 ``query_name`` - string or None
504 If this was the execution of a :ref:`canned query <canned_queries>`, the name of that query.
505
506 ``database`` - string
507 The name of the database.
508
509 ``table`` - string or None
510 The table or view, if one is being rendered.
511
512 ``request`` - :ref:`internals_request`
513 The current HTTP request.
514
515 ``view_name`` - string
516 The name of the current view being called. ``index``, ``database``, ``table``, and ``row`` are the most important ones.
517
518 The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller.
519
520 It can also return a dictionary with the following keys. This format is **deprecated** as-of Datasette 0.49 and will be removed by Datasette 1.0.
521
522 ``body`` - string or bytes, optional
523 The response body, default empty
524
525 ``content_type`` - string, optional
526 The Content-Type header, default ``text/plain``
527
528 ``status_code`` - integer, optional
529 The HTTP status code, default 200
530
531 ``headers`` - dictionary, optional
532 Extra HTTP headers to be returned in the response.
533
534 An example of an output renderer callback function:
535
536 .. code-block:: python
537
538 def render_demo():
539 return Response.text("Hello World")
540
541 Here is a more complex example:
542
543 .. code-block:: python
544
545 async def render_demo(datasette, columns, rows):
546 db = datasette.get_database()
547 result = await db.execute("select sqlite_version()")
548 first_row = " | ".join(columns)
549 lines = [first_row]
550 lines.append("=" * len(first_row))
551 for row in rows:
552 lines.append(" | ".join(row))
553 return Response(
554 "\n".join(lines),
555 content_type="text/plain; charset=utf-8",
556 headers={"x-sqlite-version": result.first()[0]},
557 )
558
559 And here is an example ``can_render`` function which returns ``True`` only if the query results contain the columns ``atom_id``, ``atom_title`` and ``atom_updated``:
560
561 .. code-block:: python
562
563 def can_render_demo(columns):
564 return {
565 "atom_id",
566 "atom_title",
567 "atom_updated",
568 }.issubset(columns)
569
570 Examples: `datasette-atom <https://datasette.io/plugins/datasette-atom>`_, `datasette-ics <https://datasette.io/plugins/datasette-ics>`_, `datasette-geojson <https://datasette.io/plugins/datasette-geojson>`__, `datasette-copyable <https://datasette.io/plugins/datasette-copyable>`__
571
572 .. _plugin_register_routes:
573
574 register_routes(datasette)
575 --------------------------
576
577 ``datasette`` - :ref:`internals_datasette`
578 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
579
580 Register additional view functions to execute for specified URL routes.
581
582 Return a list of ``(regex, view_function)`` pairs, something like this:
583
584 .. code-block:: python
585
586 from datasette import hookimpl, Response
587 import html
588
589
590 async def hello_from(request):
591 name = request.url_vars["name"]
592 return Response.html(
593 "Hello from {}".format(html.escape(name))
594 )
595
596
597 @hookimpl
598 def register_routes():
599 return [(r"^/hello-from/(?P<name>.*)$", hello_from)]
600
601 The view functions can take a number of different optional arguments. The corresponding argument will be passed to your function depending on its named parameters - a form of dependency injection.
602
603 The optional view function arguments are as follows:
604
605 ``datasette`` - :ref:`internals_datasette`
606 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
607
608 ``request`` - :ref:`internals_request`
609 The current HTTP request.
610
611 ``scope`` - dictionary
612 The incoming ASGI scope dictionary.
613
614 ``send`` - function
615 The ASGI send function.
616
617 ``receive`` - function
618 The ASGI receive function.
619
620 The view function can be a regular function or an ``async def`` function, depending on if it needs to use any ``await`` APIs.
621
622 The function can either return a :ref:`internals_response` or it can return nothing and instead respond directly to the request using the ASGI ``send`` function (for advanced uses only).
623
624 It can also raise the ``datasette.NotFound`` exception to return a 404 not found error, or the ``datasette.Forbidden`` exception for a 403 forbidden.
625
626 See :ref:`writing_plugins_designing_urls` for tips on designing the URL routes used by your plugin.
627
628 Examples: `datasette-auth-github <https://datasette.io/plugins/datasette-auth-github>`__, `datasette-psutil <https://datasette.io/plugins/datasette-psutil>`__
629
630 .. _plugin_hook_register_commands:
631
632 register_commands(cli)
633 ----------------------
634
635 ``cli`` - the root Datasette `Click command group <https://click.palletsprojects.com/en/latest/commands/#callback-invocation>`__
636 Use this to register additional CLI commands
637
638 Register additional CLI commands that can be run using ``datsette yourcommand ...``. This provides a mechanism by which plugins can add new CLI commands to Datasette.
639
640 This example registers a new ``datasette verify file1.db file2.db`` command that checks if the provided file paths are valid SQLite databases:
641
642 .. code-block:: python
643
644 from datasette import hookimpl
645 import click
646 import sqlite3
647
648
649 @hookimpl
650 def register_commands(cli):
651 @cli.command()
652 @click.argument(
653 "files", type=click.Path(exists=True), nargs=-1
654 )
655 def verify(files):
656 "Verify that files can be opened by Datasette"
657 for file in files:
658 conn = sqlite3.connect(str(file))
659 try:
660 conn.execute("select * from sqlite_master")
661 except sqlite3.DatabaseError:
662 raise click.ClickException(
663 "Invalid database: {}".format(file)
664 )
665
666 The new command can then be executed like so::
667
668 datasette verify fixtures.db
669
670 Help text (from the docstring for the function plus any defined Click arguments or options) will become available using::
671
672 datasette verify --help
673
674 Plugins can register multiple commands by making multiple calls to the ``@cli.command()`` decorator. Consult the `Click documentation <https://click.palletsprojects.com/>`__ for full details on how to build a CLI command, including how to define arguments and options.
675
676 Note that ``register_commands()`` plugins cannot used with the :ref:`--plugins-dir mechanism <writing_plugins_one_off>` - they need to be installed into the same virtual environment as Datasette using ``pip install``. Provided it has a ``setup.py`` file (see :ref:`writing_plugins_packaging`) you can run ``pip install`` directly against the directory in which you are developing your plugin like so::
677
678 pip install -e path/to/my/datasette-plugin
679
680 Examples: `datasette-auth-passwords <https://datasette.io/plugins/datasette-auth-passwords>`__, `datasette-verify <https://datasette.io/plugins/datasette-verify>`__
681
682 .. _plugin_register_facet_classes:
683
684 register_facet_classes()
685 ------------------------
686
687 Return a list of additional Facet subclasses to be registered.
688
689 .. warning::
690 The design of this plugin hook is unstable and may change. See `issue 830 <https://github.com/simonw/datasette/issues/830>`__.
691
692 Each Facet subclass implements a new type of facet operation. The class should look like this:
693
694 .. code-block:: python
695
696 class SpecialFacet(Facet):
697 # This key must be unique across all facet classes:
698 type = "special"
699
700 async def suggest(self):
701 # Use self.sql and self.params to suggest some facets
702 suggested_facets = []
703 suggested_facets.append(
704 {
705 "name": column, # Or other unique name
706 # Construct the URL that will enable this facet:
707 "toggle_url": self.ds.absolute_url(
708 self.request,
709 path_with_added_args(
710 self.request, {"_facet": column}
711 ),
712 ),
713 }
714 )
715 return suggested_facets
716
717 async def facet_results(self):
718 # This should execute the facet operation and return results, again
719 # using self.sql and self.params as the starting point
720 facet_results = []
721 facets_timed_out = []
722 facet_size = self.get_facet_size()
723 # Do some calculations here...
724 for column in columns_selected_for_facet:
725 try:
726 facet_results_values = []
727 # More calculations...
728 facet_results_values.append(
729 {
730 "value": value,
731 "label": label,
732 "count": count,
733 "toggle_url": self.ds.absolute_url(
734 self.request, toggle_path
735 ),
736 "selected": selected,
737 }
738 )
739 facet_results.append(
740 {
741 "name": column,
742 "results": facet_results_values,
743 "truncated": len(facet_rows_results)
744 > facet_size,
745 }
746 )
747 except QueryInterrupted:
748 facets_timed_out.append(column)
749
750 return facet_results, facets_timed_out
751
752 See `datasette/facets.py <https://github.com/simonw/datasette/blob/main/datasette/facets.py>`__ for examples of how these classes can work.
753
754 The plugin hook can then be used to register the new facet class like this:
755
756 .. code-block:: python
757
758 @hookimpl
759 def register_facet_classes():
760 return [SpecialFacet]
761
762 .. _plugin_asgi_wrapper:
763
764 asgi_wrapper(datasette)
765 -----------------------
766
767 Return an `ASGI <https://asgi.readthedocs.io/>`__ middleware wrapper function that will be applied to the Datasette ASGI application.
768
769 This is a very powerful hook. You can use it to manipulate the entire Datasette response, or even to configure new URL routes that will be handled by your own custom code.
770
771 You can write your ASGI code directly against the low-level specification, or you can use the middleware utilities provided by an ASGI framework such as `Starlette <https://www.starlette.io/middleware/>`__.
772
773 This example plugin adds a ``x-databases`` HTTP header listing the currently attached databases:
774
775 .. code-block:: python
776
777 from datasette import hookimpl
778 from functools import wraps
779
780
781 @hookimpl
782 def asgi_wrapper(datasette):
783 def wrap_with_databases_header(app):
784 @wraps(app)
785 async def add_x_databases_header(
786 scope, receive, send
787 ):
788 async def wrapped_send(event):
789 if event["type"] == "http.response.start":
790 original_headers = (
791 event.get("headers") or []
792 )
793 event = {
794 "type": event["type"],
795 "status": event["status"],
796 "headers": original_headers
797 + [
798 [
799 b"x-databases",
800 ", ".join(
801 datasette.databases.keys()
802 ).encode("utf-8"),
803 ]
804 ],
805 }
806 await send(event)
807
808 await app(scope, receive, wrapped_send)
809
810 return add_x_databases_header
811
812 return wrap_with_databases_header
813
814 Examples: `datasette-cors <https://datasette.io/plugins/datasette-cors>`__, `datasette-pyinstrument <https://datasette.io/plugins/datasette-pyinstrument>`__, `datasette-total-page-time <https://datasette.io/plugins/datasette-total-page-time>`__
815
816 .. _plugin_hook_startup:
817
818 startup(datasette)
819 ------------------
820
821 This hook fires when the Datasette application server first starts up. You can implement a regular function, for example to validate required plugin configuration:
822
823 .. code-block:: python
824
825 @hookimpl
826 def startup(datasette):
827 config = datasette.plugin_config("my-plugin") or {}
828 assert (
829 "required-setting" in config
830 ), "my-plugin requires setting required-setting"
831
832 Or you can return an async function which will be awaited on startup. Use this option if you need to make any database queries:
833
834 .. code-block:: python
835
836 @hookimpl
837 def startup(datasette):
838 async def inner():
839 db = datasette.get_database()
840 if "my_table" not in await db.table_names():
841 await db.execute_write(
842 """
843 create table my_table (mycol text)
844 """
845 )
846
847 return inner
848
849 Potential use-cases:
850
851 * Run some initialization code for the plugin
852 * Create database tables that a plugin needs on startup
853 * Validate the metadata configuration for a plugin on startup, and raise an error if it is invalid
854
855 .. note::
856
857 If you are writing :ref:`unit tests <testing_plugins>` for a plugin that uses this hook and doesn't exercise Datasette by sending
858 any simulated requests through it you will need to explicitly call ``await ds.invoke_startup()`` in your tests. An example:
859
860 .. code-block:: python
861
862 @pytest.mark.asyncio
863 async def test_my_plugin():
864 ds = Datasette()
865 await ds.invoke_startup()
866 # Rest of test goes here
867
868 Examples: `datasette-saved-queries <https://datasette.io/plugins/datasette-saved-queries>`__, `datasette-init <https://datasette.io/plugins/datasette-init>`__
869
870 .. _plugin_hook_canned_queries:
871
872 canned_queries(datasette, database, actor)
873 ------------------------------------------
874
875 ``datasette`` - :ref:`internals_datasette`
876 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
877
878 ``database`` - string
879 The name of the database.
880
881 ``actor`` - dictionary or None
882 The currently authenticated :ref:`actor <authentication_actor>`.
883
884 Use this hook to return a dictionary of additional :ref:`canned query <canned_queries>` definitions for the specified database. The return value should be the same shape as the JSON described in the :ref:`canned query <canned_queries>` documentation.
885
886 .. code-block:: python
887
888 from datasette import hookimpl
889
890
891 @hookimpl
892 def canned_queries(datasette, database):
893 if database == "mydb":
894 return {
895 "my_query": {
896 "sql": "select * from my_table where id > :min_id"
897 }
898 }
899
900 The hook can alternatively return an awaitable function that returns a list. Here's an example that returns queries that have been stored in the ``saved_queries`` database table, if one exists:
901
902 .. code-block:: python
903
904 from datasette import hookimpl
905
906
907 @hookimpl
908 def canned_queries(datasette, database):
909 async def inner():
910 db = datasette.get_database(database)
911 if await db.table_exists("saved_queries"):
912 results = await db.execute(
913 "select name, sql from saved_queries"
914 )
915 return {
916 result["name"]: {"sql": result["sql"]}
917 for result in results
918 }
919
920 return inner
921
922 The actor parameter can be used to include the currently authenticated actor in your decision. Here's an example that returns saved queries that were saved by that actor:
923
924 .. code-block:: python
925
926 from datasette import hookimpl
927
928
929 @hookimpl
930 def canned_queries(datasette, database, actor):
931 async def inner():
932 db = datasette.get_database(database)
933 if actor is not None and await db.table_exists(
934 "saved_queries"
935 ):
936 results = await db.execute(
937 "select name, sql from saved_queries where actor_id = :id",
938 {"id": actor["id"]},
939 )
940 return {
941 result["name"]: {"sql": result["sql"]}
942 for result in results
943 }
944
945 return inner
946
947 Example: `datasette-saved-queries <https://datasette.io/plugins/datasette-saved-queries>`__
948
949 .. _plugin_hook_actor_from_request:
950
951 actor_from_request(datasette, request)
952 --------------------------------------
953
954 ``datasette`` - :ref:`internals_datasette`
955 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
956
957 ``request`` - :ref:`internals_request`
958 The current HTTP request.
959
960 This is part of Datasette's :ref:`authentication and permissions system <authentication>`. The function should attempt to authenticate an actor (either a user or an API actor of some sort) based on information in the request.
961
962 If it cannot authenticate an actor, it should return ``None``. Otherwise it should return a dictionary representing that actor.
963
964 Here's an example that authenticates the actor based on an incoming API key:
965
966 .. code-block:: python
967
968 from datasette import hookimpl
969 import secrets
970
971 SECRET_KEY = "this-is-a-secret"
972
973
974 @hookimpl
975 def actor_from_request(datasette, request):
976 authorization = (
977 request.headers.get("authorization") or ""
978 )
979 expected = "Bearer {}".format(SECRET_KEY)
980
981 if secrets.compare_digest(authorization, expected):
982 return {"id": "bot"}
983
984 If you install this in your plugins directory you can test it like this::
985
986 $ curl -H 'Authorization: Bearer this-is-a-secret' http://localhost:8003/-/actor.json
987
988 Instead of returning a dictionary, this function can return an awaitable function which itself returns either ``None`` or a dictionary. This is useful for authentication functions that need to make a database query - for example:
989
990 .. code-block:: python
991
992 from datasette import hookimpl
993
994
995 @hookimpl
996 def actor_from_request(datasette, request):
997 async def inner():
998 token = request.args.get("_token")
999 if not token:
1000 return None
1001 # Look up ?_token=xxx in sessions table
1002 result = await datasette.get_database().execute(
1003 "select count(*) from sessions where token = ?",
1004 [token],
1005 )
1006 if result.first()[0]:
1007 return {"token": token}
1008 else:
1009 return None
1010
1011 return inner
1012
1013 Example: `datasette-auth-tokens <https://datasette.io/plugins/datasette-auth-tokens>`_
1014
1015 .. _plugin_hook_filters_from_request:
1016
1017 filters_from_request(request, database, table, datasette)
1018 ---------------------------------------------------------
1019
1020 ``request`` - :ref:`internals_request`
1021 The current HTTP request.
1022
1023 ``database`` - string
1024 The name of the database.
1025
1026 ``table`` - string
1027 The name of the table.
1028
1029 ``datasette`` - :ref:`internals_datasette`
1030 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1031
1032 This hook runs on the :ref:`table <TableView>` page, and can influence the ``where`` clause of the SQL query used to populate that page, based on query string arguments on the incoming request.
1033
1034 The hook should return an instance of ``datasette.filters.FilterArguments`` which has one required and three optional arguments:
1035
1036 .. code-block:: python
1037
1038 return FilterArguments(
1039 where_clauses=["id > :max_id"],
1040 params={"max_id": 5},
1041 human_descriptions=["max_id is greater than 5"],
1042 extra_context={},
1043 )
1044
1045 The arguments to the ``FilterArguments`` class constructor are as follows:
1046
1047 ``where_clauses`` - list of strings, required
1048 A list of SQL fragments that will be inserted into the SQL query, joined by the ``and`` operator. These can include ``:named`` parameters which will be populated using data in ``params``.
1049 ``params`` - dictionary, optional
1050 Additional keyword arguments to be used when the query is executed. These should match any ``:arguments`` in the where clauses.
1051 ``human_descriptions`` - list of strings, optional
1052 These strings will be included in the human-readable description at the top of the page and the page ``<title>``.
1053 ``extra_context`` - dictionary, optional
1054 Additional context variables that should be made available to the ``table.html`` template when it is rendered.
1055
1056 This example plugin causes 0 results to be returned if ``?_nothing=1`` is added to the URL:
1057
1058 .. code-block:: python
1059
1060 from datasette import hookimpl
1061 from datasette.filters import FilterArguments
1062
1063
1064 @hookimpl
1065 def filters_from_request(self, request):
1066 if request.args.get("_nothing"):
1067 return FilterArguments(
1068 ["1 = 0"], human_descriptions=["NOTHING"]
1069 )
1070
1071 Example: `datasette-leaflet-freedraw <https://datasette.io/plugins/datasette-leaflet-freedraw>`_
1072
1073 .. _plugin_hook_permission_allowed:
1074
1075 permission_allowed(datasette, actor, action, resource)
1076 ------------------------------------------------------
1077
1078 ``datasette`` - :ref:`internals_datasette`
1079 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1080
1081 ``actor`` - dictionary
1082 The current actor, as decided by :ref:`plugin_hook_actor_from_request`.
1083
1084 ``action`` - string
1085 The action to be performed, e.g. ``"edit-table"``.
1086
1087 ``resource`` - string or None
1088 An identifier for the individual resource, e.g. the name of the table.
1089
1090 Called to check that an actor has permission to perform an action on a resource. Can return ``True`` if the action is allowed, ``False`` if the action is not allowed or ``None`` if the plugin does not have an opinion one way or the other.
1091
1092 Here's an example plugin which randomly selects if a permission should be allowed or denied, except for ``view-instance`` which always uses the default permission scheme instead.
1093
1094 .. code-block:: python
1095
1096 from datasette import hookimpl
1097 import random
1098
1099
1100 @hookimpl
1101 def permission_allowed(action):
1102 if action != "view-instance":
1103 # Return True or False at random
1104 return random.random() > 0.5
1105 # Returning None falls back to default permissions
1106
1107 This function can alternatively return an awaitable function which itself returns ``True``, ``False`` or ``None``. You can use this option if you need to execute additional database queries using ``await datasette.execute(...)``.
1108
1109 Here's an example that allows users to view the ``admin_log`` table only if their actor ``id`` is present in the ``admin_users`` table. It aso disallows arbitrary SQL queries for the ``staff.db`` database for all users.
1110
1111 .. code-block:: python
1112
1113 @hookimpl
1114 def permission_allowed(datasette, actor, action, resource):
1115 async def inner():
1116 if action == "execute-sql" and resource == "staff":
1117 return False
1118 if action == "view-table" and resource == (
1119 "staff",
1120 "admin_log",
1121 ):
1122 if not actor:
1123 return False
1124 user_id = actor["id"]
1125 return await datasette.get_database(
1126 "staff"
1127 ).execute(
1128 "select count(*) from admin_users where user_id = :user_id",
1129 {"user_id": user_id},
1130 )
1131
1132 return inner
1133
1134 See :ref:`built-in permissions <permissions>` for a full list of permissions that are included in Datasette core.
1135
1136 Example: `datasette-permissions-sql <https://datasette.io/plugins/datasette-permissions-sql>`_
1137
1138 .. _plugin_hook_register_magic_parameters:
1139
1140 register_magic_parameters(datasette)
1141 ------------------------------------
1142
1143 ``datasette`` - :ref:`internals_datasette`
1144 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``.
1145
1146 :ref:`canned_queries_magic_parameters` can be used to add automatic parameters to :ref:`canned queries <canned_queries>`. This plugin hook allows additional magic parameters to be defined by plugins.
1147
1148 Magic parameters all take this format: ``_prefix_rest_of_parameter``. The prefix indicates which magic parameter function should be called - the rest of the parameter is passed as an argument to that function.
1149
1150 To register a new function, return it as a tuple of ``(string prefix, function)`` from this hook. The function you register should take two arguments: ``key`` and ``request``, where ``key`` is the ``rest_of_parameter`` portion of the parameter and ``request`` is the current :ref:`internals_request`.
1151
1152 This example registers two new magic parameters: ``:_request_http_version`` returning the HTTP version of the current request, and ``:_uuid_new`` which returns a new UUID:
1153
1154 .. code-block:: python
1155
1156 from uuid import uuid4
1157
1158
1159 def uuid(key, request):
1160 if key == "new":
1161 return str(uuid4())
1162 else:
1163 raise KeyError
1164
1165
1166 def request(key, request):
1167 if key == "http_version":
1168 return request.scope["http_version"]
1169 else:
1170 raise KeyError
1171
1172
1173 @hookimpl
1174 def register_magic_parameters(datasette):
1175 return [
1176 ("request", request),
1177 ("uuid", uuid),
1178 ]
1179
1180 .. _plugin_hook_forbidden:
1181
1182 forbidden(datasette, request, message)
1183 --------------------------------------
1184
1185 ``datasette`` - :ref:`internals_datasette`
1186 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to render templates or execute SQL queries.
1187
1188 ``request`` - :ref:`internals_request`
1189 The current HTTP request.
1190
1191 ``message`` - string
1192 A message hinting at why the request was forbidden.
1193
1194 Plugins can use this to customize how Datasette responds when a 403 Forbidden error occurs - usually because a page failed a permission check, see :ref:`authentication_permissions`.
1195
1196 If a plugin hook wishes to react to the error, it should return a :ref:`Response object <internals_response>`.
1197
1198 This example returns a redirect to a ``/-/login`` page:
1199
1200 .. code-block:: python
1201
1202 from datasette import hookimpl
1203 from urllib.parse import urlencode
1204
1205
1206 @hookimpl
1207 def forbidden(request, message):
1208 return Response.redirect(
1209 "/-/login?=" + urlencode({"message": message})
1210 )
1211
1212 The function can alternatively return an awaitable function if it needs to make any asynchronous method calls. This example renders a template:
1213
1214 .. code-block:: python
1215
1216 from datasette import hookimpl, Response
1217
1218
1219 @hookimpl
1220 def forbidden(datasette):
1221 async def inner():
1222 return Response.html(
1223 await datasette.render_template(
1224 "render_message.html", request=request
1225 )
1226 )
1227
1228 return inner
1229
1230 .. _plugin_hook_handle_exception:
1231
1232 handle_exception(datasette, request, exception)
1233 -----------------------------------------------
1234
1235 ``datasette`` - :ref:`internals_datasette`
1236 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to render templates or execute SQL queries.
1237
1238 ``request`` - :ref:`internals_request`
1239 The current HTTP request.
1240
1241 ``exception`` - ``Exception``
1242 The exception that was raised.
1243
1244 This hook is called any time an unexpected exception is raised. You can use it to record the exception.
1245
1246 If your handler returns a ``Response`` object it will be returned to the client in place of the default Datasette error page.
1247
1248 The handler can return a response directly, or it can return return an awaitable function that returns a response.
1249
1250 This example logs an error to `Sentry <https://sentry.io/>`__ and then renders a custom error page:
1251
1252 .. code-block:: python
1253
1254 from datasette import hookimpl, Response
1255 import sentry_sdk
1256
1257
1258 @hookimpl
1259 def handle_exception(datasette, exception):
1260 sentry_sdk.capture_exception(exception)
1261
1262 async def inner():
1263 return Response.html(
1264 await datasette.render_template(
1265 "custom_error.html", request=request
1266 )
1267 )
1268
1269 return inner
1270
1271 Example: `datasette-sentry <https://datasette.io/plugins/datasette-sentry>`_
1272
1273 .. _plugin_hook_menu_links:
1274
1275 menu_links(datasette, actor, request)
1276 -------------------------------------
1277
1278 ``datasette`` - :ref:`internals_datasette`
1279 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1280
1281 ``actor`` - dictionary or None
1282 The currently authenticated :ref:`actor <authentication_actor>`.
1283
1284 ``request`` - :ref:`internals_request` or None
1285 The current HTTP request. This can be ``None`` if the request object is not available.
1286
1287 This hook allows additional items to be included in the menu displayed by Datasette's top right menu icon.
1288
1289 The hook should return a list of ``{"href": "...", "label": "..."}`` menu items. These will be added to the menu.
1290
1291 It can alternatively return an ``async def`` awaitable function which returns a list of menu items.
1292
1293 This example adds a new menu item but only if the signed in user is ``"root"``:
1294
1295 .. code-block:: python
1296
1297 from datasette import hookimpl
1298
1299
1300 @hookimpl
1301 def menu_links(datasette, actor):
1302 if actor and actor.get("id") == "root":
1303 return [
1304 {
1305 "href": datasette.urls.path(
1306 "/-/edit-schema"
1307 ),
1308 "label": "Edit schema",
1309 },
1310 ]
1311
1312 Using :ref:`internals_datasette_urls` here ensures that links in the menu will take the :ref:`setting_base_url` setting into account.
1313
1314 Examples: `datasette-search-all <https://datasette.io/plugins/datasette-search-all>`_, `datasette-graphql <https://datasette.io/plugins/datasette-graphql>`_
1315
1316 .. _plugin_hook_table_actions:
1317
1318 table_actions(datasette, actor, database, table, request)
1319 ---------------------------------------------------------
1320
1321 ``datasette`` - :ref:`internals_datasette`
1322 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1323
1324 ``actor`` - dictionary or None
1325 The currently authenticated :ref:`actor <authentication_actor>`.
1326
1327 ``database`` - string
1328 The name of the database.
1329
1330 ``table`` - string
1331 The name of the table.
1332
1333 ``request`` - :ref:`internals_request` or None
1334 The current HTTP request. This can be ``None`` if the request object is not available.
1335
1336 This hook allows table actions to be displayed in a menu accessed via an action icon at the top of the table page. It should return a list of ``{"href": "...", "label": "..."}`` menu items.
1337
1338 It can alternatively return an ``async def`` awaitable function which returns a list of menu items.
1339
1340 This example adds a new table action if the signed in user is ``"root"``:
1341
1342 .. code-block:: python
1343
1344 from datasette import hookimpl
1345
1346
1347 @hookimpl
1348 def table_actions(datasette, actor, database, table):
1349 if actor and actor.get("id") == "root":
1350 return [
1351 {
1352 "href": datasette.urls.path(
1353 "/-/edit-schema/{}/{}".format(
1354 database, table
1355 )
1356 ),
1357 "label": "Edit schema for this table",
1358 }
1359 ]
1360
1361 Example: `datasette-graphql <https://datasette.io/plugins/datasette-graphql>`_
1362
1363 .. _plugin_hook_database_actions:
1364
1365 database_actions(datasette, actor, database, request)
1366 -----------------------------------------------------
1367
1368 ``datasette`` - :ref:`internals_datasette`
1369 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1370
1371 ``actor`` - dictionary or None
1372 The currently authenticated :ref:`actor <authentication_actor>`.
1373
1374 ``database`` - string
1375 The name of the database.
1376
1377 ``request`` - :ref:`internals_request`
1378 The current HTTP request.
1379
1380 This hook is similar to :ref:`plugin_hook_table_actions` but populates an actions menu on the database page.
1381
1382 Example: `datasette-graphql <https://datasette.io/plugins/datasette-graphql>`_
1383
1384 .. _plugin_hook_skip_csrf:
1385
1386 skip_csrf(datasette, scope)
1387 ---------------------------
1388
1389 ``datasette`` - :ref:`internals_datasette`
1390 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``, or to execute SQL queries.
1391
1392 ``scope`` - dictionary
1393 The `ASGI scope <https://asgi.readthedocs.io/en/latest/specs/www.html#http-connection-scope>`__ for the incoming HTTP request.
1394
1395 This hook can be used to skip :ref:`internals_csrf` for a specific incoming request. For example, you might have a custom path at ``/submit-comment`` which is designed to accept comments from anywhere, whether or not the incoming request originated on the site and has an accompanying CSRF token.
1396
1397 This example will disable CSRF protection for that specific URL path:
1398
1399 .. code-block:: python
1400
1401 from datasette import hookimpl
1402
1403
1404 @hookimpl
1405 def skip_csrf(scope):
1406 return scope["path"] == "/submit-comment"
1407
1408 If any of the currently active ``skip_csrf()`` plugin hooks return ``True``, CSRF protection will be skipped for the request.
1409
1410 .. _plugin_hook_get_metadata:
1411
1412 get_metadata(datasette, key, database, table)
1413 ---------------------------------------------
1414
1415 ``datasette`` - :ref:`internals_datasette`
1416 You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``.
1417
1418 ``actor`` - dictionary or None
1419 The currently authenticated :ref:`actor <authentication_actor>`.
1420
1421 ``database`` - string or None
1422 The name of the database metadata is being asked for.
1423
1424 ``table`` - string or None
1425 The name of the table.
1426
1427 ``key`` - string or None
1428 The name of the key for which data is being asked for.
1429
1430 This hook is responsible for returning a dictionary corresponding to Datasette :ref:`metadata`. This function is passed the ``database``, ``table`` and ``key`` which were passed to the upstream internal request for metadata. Regardless, it is important to return a global metadata object, where ``"databases": []`` would be a top-level key. The dictionary returned here, will be merged with, and overwritten by, the contents of the physical ``metadata.yaml`` if one is present.
1431
1432 .. warning::
1433 The design of this plugin hook does not currently provide a mechanism for interacting with async code, and may change in the future. See `issue 1384 <https://github.com/simonw/datasette/issues/1384>`__.
1434
1435 .. code-block:: python
1436
1437 @hookimpl
1438 def get_metadata(datasette, key, database, table):
1439 metadata = {
1440 "title": "This will be the Datasette landing page title!",
1441 "description": get_instance_description(datasette),
1442 "databases": [],
1443 }
1444 for db_name, db_data_dict in get_my_database_meta(
1445 datasette, database, table, key
1446 ):
1447 metadata["databases"][db_name] = db_data_dict
1448 # whatever we return here will be merged with any other plugins using this hook and
1449 # will be overwritten by a local metadata.yaml if one exists!
1450 return metadata
1451
1452 Example: `datasette-remote-metadata plugin <https://datasette.io/plugins/datasette-remote-metadata>`__