Debian Codegraph @

docs/internals.rst

raw
1 .. _internals:
2
3 =======================
4 Internals for plugins
5 =======================
6
7 Many :ref:`plugin_hooks` are passed objects that provide access to internal Datasette functionality. The interface to these objects should not be considered stable with the exception of methods that are documented here.
8
9 .. _internals_request:
10
11 Request object
12 ==============
13
14 The request object is passed to various plugin hooks. It represents an incoming HTTP request. It has the following properties:
15
16 ``.scope`` - dictionary
17 The ASGI scope that was used to construct this request, described in the `ASGI HTTP connection scope <https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope>`__ specification.
18
19 ``.method`` - string
20 The HTTP method for this request, usually ``GET`` or ``POST``.
21
22 ``.url`` - string
23 The full URL for this request, e.g. ``https://latest.datasette.io/fixtures``.
24
25 ``.scheme`` - string
26 The request scheme - usually ``https`` or ``http``.
27
28 ``.headers`` - dictionary (str -> str)
29 A dictionary of incoming HTTP request headers. Header names have been converted to lowercase.
30
31 ``.cookies`` - dictionary (str -> str)
32 A dictionary of incoming cookies
33
34 ``.host`` - string
35 The host header from the incoming request, e.g. ``latest.datasette.io`` or ``localhost``.
36
37 ``.path`` - string
38 The path of the request excluding the query string, e.g. ``/fixtures``.
39
40 ``.full_path`` - string
41 The path of the request including the query string if one is present, e.g. ``/fixtures?sql=select+sqlite_version()``.
42
43 ``.query_string`` - string
44 The query string component of the request, without the ``?`` - e.g. ``name__contains=sam&age__gt=10``.
45
46 ``.args`` - MultiParams
47 An object representing the parsed query string parameters, see below.
48
49 ``.url_vars`` - dictionary (str -> str)
50 Variables extracted from the URL path, if that path was defined using a regular expression. See :ref:`plugin_register_routes`.
51
52 ``.actor`` - dictionary (str -> Any) or None
53 The currently authenticated actor (see :ref:`actors <authentication_actor>`), or ``None`` if the request is unauthenticated.
54
55 The object also has two awaitable methods:
56
57 ``await request.post_vars()`` - dictionary
58 Returns a dictionary of form variables that were submitted in the request body via ``POST``. Don't forget to read about :ref:`internals_csrf`!
59
60 ``await request.post_body()`` - bytes
61 Returns the un-parsed body of a request submitted by ``POST`` - useful for things like incoming JSON data.
62
63 And a class method that can be used to create fake request objects for use in tests:
64
65 ``fake(path_with_query_string, method="GET", scheme="http", url_vars=None)``
66 Returns a ``Request`` instance for the specified path and method. For example:
67
68 .. code-block:: python
69
70 from datasette import Request
71 from pprint import pprint
72
73 request = Request.fake(
74 "/fixtures/facetable/",
75 url_vars={"database": "fixtures", "table": "facetable"},
76 )
77 pprint(request.scope)
78
79 This outputs::
80
81 {'http_version': '1.1',
82 'method': 'GET',
83 'path': '/fixtures/facetable/',
84 'query_string': b'',
85 'raw_path': b'/fixtures/facetable/',
86 'scheme': 'http',
87 'type': 'http',
88 'url_route': {'kwargs': {'database': 'fixtures', 'table': 'facetable'}}}
89
90 .. _internals_multiparams:
91
92 The MultiParams class
93 =====================
94
95 ``request.args`` is a ``MultiParams`` object - a dictionary-like object which provides access to query string parameters that may have multiple values.
96
97 Consider the query string ``?foo=1&foo=2&bar=3`` - with two values for ``foo`` and one value for ``bar``.
98
99 ``request.args[key]`` - string
100 Returns the first value for that key, or raises a ``KeyError`` if the key is missing. For the above example ``request.args["foo"]`` would return ``"1"``.
101
102 ``request.args.get(key)`` - string or None
103 Returns the first value for that key, or ``None`` if the key is missing. Pass a second argument to specify a different default, e.g. ``q = request.args.get("q", "")``.
104
105 ``request.args.getlist(key)`` - list of strings
106 Returns the list of strings for that key. ``request.args.getlist("foo")`` would return ``["1", "2"]`` in the above example. ``request.args.getlist("bar")`` would return ``["3"]``. If the key is missing an empty list will be returned.
107
108 ``request.args.keys()`` - list of strings
109 Returns the list of available keys - for the example this would be ``["foo", "bar"]``.
110
111 ``key in request.args`` - True or False
112 You can use ``if key in request.args`` to check if a key is present.
113
114 ``for key in request.args`` - iterator
115 This lets you loop through every available key.
116
117 ``len(request.args)`` - integer
118 Returns the number of keys.
119
120 .. _internals_response:
121
122 Response class
123 ==============
124
125 The ``Response`` class can be returned from view functions that have been registered using the :ref:`plugin_register_routes` hook.
126
127 The ``Response()`` constructor takes the following arguments:
128
129 ``body`` - string
130 The body of the response.
131
132 ``status`` - integer (optional)
133 The HTTP status - defaults to 200.
134
135 ``headers`` - dictionary (optional)
136 A dictionary of extra HTTP headers, e.g. ``{"x-hello": "world"}``.
137
138 ``content_type`` - string (optional)
139 The content-type for the response. Defaults to ``text/plain``.
140
141 For example:
142
143 .. code-block:: python
144
145 from datasette.utils.asgi import Response
146
147 response = Response(
148 "<xml>This is XML</xml>",
149 content_type="application/xml; charset=utf-8",
150 )
151
152 The quickest way to create responses is using the ``Response.text(...)``, ``Response.html(...)``, ``Response.json(...)`` or ``Response.redirect(...)`` helper methods:
153
154 .. code-block:: python
155
156 from datasette.utils.asgi import Response
157
158 html_response = Response.html("This is HTML")
159 json_response = Response.json({"this_is": "json"})
160 text_response = Response.text(
161 "This will become utf-8 encoded text"
162 )
163 # Redirects are served as 302, unless you pass status=301:
164 redirect_response = Response.redirect(
165 "https://latest.datasette.io/"
166 )
167
168 Each of these responses will use the correct corresponding content-type - ``text/html; charset=utf-8``, ``application/json; charset=utf-8`` or ``text/plain; charset=utf-8`` respectively.
169
170 Each of the helper methods take optional ``status=`` and ``headers=`` arguments, documented above.
171
172 .. _internals_response_asgi_send:
173
174 Returning a response with .asgi_send(send)
175 ------------------------------------------
176
177 In most cases you will return ``Response`` objects from your own view functions. You can also use a ``Response`` instance to respond at a lower level via ASGI, for example if you are writing code that uses the :ref:`plugin_asgi_wrapper` hook.
178
179 Create a ``Response`` object and then use ``await response.asgi_send(send)``, passing the ASGI ``send`` function. For example:
180
181 .. code-block:: python
182
183 async def require_authorization(scope, receive, send):
184 response = Response.text(
185 "401 Authorization Required",
186 headers={
187 "www-authenticate": 'Basic realm="Datasette", charset="UTF-8"'
188 },
189 status=401,
190 )
191 await response.asgi_send(send)
192
193 .. _internals_response_set_cookie:
194
195 Setting cookies with response.set_cookie()
196 ------------------------------------------
197
198 To set cookies on the response, use the ``response.set_cookie(...)`` method. The method signature looks like this:
199
200 .. code-block:: python
201
202 def set_cookie(
203 self,
204 key,
205 value="",
206 max_age=None,
207 expires=None,
208 path="/",
209 domain=None,
210 secure=False,
211 httponly=False,
212 samesite="lax",
213 ): ...
214
215 You can use this with :ref:`datasette.sign() <datasette_sign>` to set signed cookies. Here's how you would set the :ref:`ds_actor cookie <authentication_ds_actor>` for use with Datasette :ref:`authentication <authentication>`:
216
217 .. code-block:: python
218
219 response = Response.redirect("/")
220 response.set_cookie(
221 "ds_actor",
222 datasette.sign({"a": {"id": "cleopaws"}}, "actor"),
223 )
224 return response
225
226 .. _internals_datasette:
227
228 Datasette class
229 ===============
230
231 This object is an instance of the ``Datasette`` class, passed to many plugin hooks as an argument called ``datasette``.
232
233 You can create your own instance of this - for example to help write tests for a plugin - like so:
234
235 .. code-block:: python
236
237 from datasette.app import Datasette
238
239 # With no arguments a single in-memory database will be attached
240 datasette = Datasette()
241
242 # The files= argument can load files from disk
243 datasette = Datasette(files=["/path/to/my-database.db"])
244
245 # Pass metadata as a JSON dictionary like this
246 datasette = Datasette(
247 files=["/path/to/my-database.db"],
248 metadata={
249 "databases": {
250 "my-database": {
251 "description": "This is my database"
252 }
253 }
254 },
255 )
256
257 Constructor parameters include:
258
259 - ``files=[...]`` - a list of database files to open
260 - ``immutables=[...]`` - a list of database files to open in immutable mode
261 - ``metadata={...}`` - a dictionary of :ref:`metadata`
262 - ``config_dir=...`` - the :ref:`configuration directory <config_dir>` to use, stored in ``datasette.config_dir``
263
264 .. _datasette_databases:
265
266 .databases
267 ----------
268
269 Property exposing a ``collections.OrderedDict`` of databases currently connected to Datasette.
270
271 The dictionary keys are the name of the database that is used in the URL - e.g. ``/fixtures`` would have a key of ``"fixtures"``. The values are :ref:`internals_database` instances.
272
273 All databases are listed, irrespective of user permissions. This means that the ``_internal`` database will always be listed here.
274
275 .. _datasette_plugin_config:
276
277 .plugin_config(plugin_name, database=None, table=None)
278 ------------------------------------------------------
279
280 ``plugin_name`` - string
281 The name of the plugin to look up configuration for. Usually this is something similar to ``datasette-cluster-map``.
282
283 ``database`` - None or string
284 The database the user is interacting with.
285
286 ``table`` - None or string
287 The table the user is interacting with.
288
289 This method lets you read plugin configuration values that were set in ``metadata.json``. See :ref:`writing_plugins_configuration` for full details of how this method should be used.
290
291 The return value will be the value from the configuration file - usually a dictionary.
292
293 If the plugin is not configured the return value will be ``None``.
294
295 .. _datasette_render_template:
296
297 await .render_template(template, context=None, request=None)
298 ------------------------------------------------------------
299
300 ``template`` - string, list of strings or jinja2.Template
301 The template file to be rendered, e.g. ``my_plugin.html``. Datasette will search for this file first in the ``--template-dir=`` location, if it was specified - then in the plugin's bundled templates and finally in Datasette's set of default templates.
302
303 If this is a list of template file names then the first one that exists will be loaded and rendered.
304
305 If this is a Jinja `Template object <https://jinja.palletsprojects.com/en/2.11.x/api/#jinja2.Template>`__ it will be used directly.
306
307 ``context`` - None or a Python dictionary
308 The context variables to pass to the template.
309
310 ``request`` - request object or None
311 If you pass a Datasette request object here it will be made available to the template.
312
313 Renders a `Jinja template <https://jinja.palletsprojects.com/en/2.11.x/>`__ using Datasette's preconfigured instance of Jinja and returns the resulting string. The template will have access to Datasette's default template functions and any functions that have been made available by other plugins.
314
315 .. _datasette_permission_allowed:
316
317 await .permission_allowed(actor, action, resource=None, default=False)
318 ----------------------------------------------------------------------
319
320 ``actor`` - dictionary
321 The authenticated actor. This is usually ``request.actor``.
322
323 ``action`` - string
324 The name of the action that is being permission checked.
325
326 ``resource`` - string or tuple, optional
327 The resource, e.g. the name of the database, or a tuple of two strings containing the name of the database and the name of the table. Only some permissions apply to a resource.
328
329 ``default`` - optional, True or False
330 Should this permission check be default allow or default deny.
331
332 Check if the given actor has :ref:`permission <authentication_permissions>` to perform the given action on the given resource.
333
334 Some permission checks are carried out against :ref:`rules defined in metadata.json <authentication_permissions_metadata>`, while other custom permissions may be decided by plugins that implement the :ref:`plugin_hook_permission_allowed` plugin hook.
335
336 If neither ``metadata.json`` nor any of the plugins provide an answer to the permission query the ``default`` argument will be returned.
337
338 See :ref:`permissions` for a full list of permission actions included in Datasette core.
339
340 .. _datasette_ensure_permissions:
341
342 await .ensure_permissions(actor, permissions)
343 ---------------------------------------------
344
345 ``actor`` - dictionary
346 The authenticated actor. This is usually ``request.actor``.
347
348 ``permissions`` - list
349 A list of permissions to check. Each permission in that list can be a string ``action`` name or a 2-tuple of ``(action, resource)``.
350
351 This method allows multiple permissions to be checked at once. It raises a ``datasette.Forbidden`` exception if any of the checks are denied before one of them is explicitly granted.
352
353 This is useful when you need to check multiple permissions at once. For example, an actor should be able to view a table if either one of the following checks returns ``True`` or not a single one of them returns ``False``:
354
355 .. code-block:: python
356
357 await self.ds.ensure_permissions(
358 request.actor,
359 [
360 ("view-table", (database, table)),
361 ("view-database", database),
362 "view-instance",
363 ],
364 )
365
366 .. _datasette_check_visibility:
367
368 await .check_visibility(actor, action=None, resource=None, permissions=None)
369 ----------------------------------------------------------------------------
370
371 ``actor`` - dictionary
372 The authenticated actor. This is usually ``request.actor``.
373
374 ``action`` - string, optional
375 The name of the action that is being permission checked.
376
377 ``resource`` - string or tuple, optional
378 The resource, e.g. the name of the database, or a tuple of two strings containing the name of the database and the name of the table. Only some permissions apply to a resource.
379
380 ``permissions`` - list of ``action`` strings or ``(action, resource)`` tuples, optional
381 Provide this instead of ``action`` and ``resource`` to check multiple permissions at once.
382
383 This convenience method can be used to answer the question "should this item be considered private, in that it is visible to me but it is not visible to anonymous users?"
384
385 It returns a tuple of two booleans, ``(visible, private)``. ``visible`` indicates if the actor can see this resource. ``private`` will be ``True`` if an anonymous user would not be able to view the resource.
386
387 This example checks if the user can access a specific table, and sets ``private`` so that a padlock icon can later be displayed:
388
389 .. code-block:: python
390
391 visible, private = await self.ds.check_visibility(
392 request.actor,
393 action="view-table",
394 resource=(database, table),
395 )
396
397 The following example runs three checks in a row, similar to :ref:`datasette_ensure_permissions`. If any of the checks are denied before one of them is explicitly granted then ``visible`` will be ``False``. ``private`` will be ``True`` if an anonymous user would not be able to view the resource.
398
399 .. code-block:: python
400
401 visible, private = await self.ds.check_visibility(
402 request.actor,
403 permissions=[
404 ("view-table", (database, table)),
405 ("view-database", database),
406 "view-instance",
407 ],
408 )
409
410 .. _datasette_get_database:
411
412 .get_database(name)
413 -------------------
414
415 ``name`` - string, optional
416 The name of the database - optional.
417
418 Returns the specified database object. Raises a ``KeyError`` if the database does not exist. Call this method without an argument to return the first connected database.
419
420 .. _datasette_add_database:
421
422 .add_database(db, name=None, route=None)
423 ----------------------------------------
424
425 ``db`` - datasette.database.Database instance
426 The database to be attached.
427
428 ``name`` - string, optional
429 The name to be used for this database . If not specified Datasette will pick one based on the filename or memory name.
430
431 ``route`` - string, optional
432 This will be used in the URL path. If not specified, it will default to the same thing as the ``name``.
433
434 The ``datasette.add_database(db)`` method lets you add a new database to the current Datasette instance.
435
436 The ``db`` parameter should be an instance of the ``datasette.database.Database`` class. For example:
437
438 .. code-block:: python
439
440 from datasette.database import Database
441
442 datasette.add_database(
443 Database(
444 datasette,
445 path="path/to/my-new-database.db",
446 )
447 )
448
449 This will add a mutable database and serve it at ``/my-new-database``.
450
451 Use ``is_mutable=False`` to add an immutable database.
452
453 ``.add_database()`` returns the Database instance, with its name set as the ``database.name`` attribute. Any time you are working with a newly added database you should use the return value of ``.add_database()``, for example:
454
455 .. code-block:: python
456
457 db = datasette.add_database(
458 Database(datasette, memory_name="statistics")
459 )
460 await db.execute_write(
461 "CREATE TABLE foo(id integer primary key)"
462 )
463
464 .. _datasette_add_memory_database:
465
466 .add_memory_database(name)
467 --------------------------
468
469 Adds a shared in-memory database with the specified name:
470
471 .. code-block:: python
472
473 datasette.add_memory_database("statistics")
474
475 This is a shortcut for the following:
476
477 .. code-block:: python
478
479 from datasette.database import Database
480
481 datasette.add_database(
482 Database(datasette, memory_name="statistics")
483 )
484
485 Using either of these pattern will result in the in-memory database being served at ``/statistics``.
486
487 .. _datasette_remove_database:
488
489 .remove_database(name)
490 ----------------------
491
492 ``name`` - string
493 The name of the database to be removed.
494
495 This removes a database that has been previously added. ``name=`` is the unique name of that database.
496
497 .. _datasette_sign:
498
499 .sign(value, namespace="default")
500 ---------------------------------
501
502 ``value`` - any serializable type
503 The value to be signed.
504
505 ``namespace`` - string, optional
506 An alternative namespace, see the `itsdangerous salt documentation <https://itsdangerous.palletsprojects.com/en/1.1.x/serializer/#the-salt>`__.
507
508 Utility method for signing values, such that you can safely pass data to and from an untrusted environment. This is a wrapper around the `itsdangerous <https://itsdangerous.palletsprojects.com/>`__ library.
509
510 This method returns a signed string, which can be decoded and verified using :ref:`datasette_unsign`.
511
512 .. _datasette_unsign:
513
514 .unsign(value, namespace="default")
515 -----------------------------------
516
517 ``signed`` - any serializable type
518 The signed string that was created using :ref:`datasette_sign`.
519
520 ``namespace`` - string, optional
521 The alternative namespace, if one was used.
522
523 Returns the original, decoded object that was passed to :ref:`datasette_sign`. If the signature is not valid this raises a ``itsdangerous.BadSignature`` exception.
524
525 .. _datasette_add_message:
526
527 .add_message(request, message, type=datasette.INFO)
528 ---------------------------------------------------
529
530 ``request`` - Request
531 The current Request object
532
533 ``message`` - string
534 The message string
535
536 ``type`` - constant, optional
537 The message type - ``datasette.INFO``, ``datasette.WARNING`` or ``datasette.ERROR``
538
539 Datasette's flash messaging mechanism allows you to add a message that will be displayed to the user on the next page that they visit. Messages are persisted in a ``ds_messages`` cookie. This method adds a message to that cookie.
540
541 You can try out these messages (including the different visual styling of the three message types) using the ``/-/messages`` debugging tool.
542
543 .. _datasette_absolute_url:
544
545 .absolute_url(request, path)
546 ----------------------------
547
548 ``request`` - Request
549 The current Request object
550
551 ``path`` - string
552 A path, for example ``/dbname/table.json``
553
554 Returns the absolute URL for the given path, including the protocol and host. For example:
555
556 .. code-block:: python
557
558 absolute_url = datasette.absolute_url(
559 request, "/dbname/table.json"
560 )
561 # Would return "http://localhost:8001/dbname/table.json"
562
563 The current request object is used to determine the hostname and protocol that should be used for the returned URL. The :ref:`setting_force_https_urls` configuration setting is taken into account.
564
565 .. _datasette_setting:
566
567 .setting(key)
568 -------------
569
570 ``key`` - string
571 The name of the setting, e.g. ``base_url``.
572
573 Returns the configured value for the specified :ref:`setting <settings>`. This can be a string, boolean or integer depending on the requested setting.
574
575 For example:
576
577 .. code-block:: python
578
579 downloads_are_allowed = datasette.setting("allow_download")
580
581 .. _internals_datasette_client:
582
583 datasette.client
584 ----------------
585
586 Plugins can make internal simulated HTTP requests to the Datasette instance within which they are running. This ensures that all of Datasette's external JSON APIs are also available to plugins, while avoiding the overhead of making an external HTTP call to access those APIs.
587
588 The ``datasette.client`` object is a wrapper around the `HTTPX Python library <https://www.python-httpx.org/>`__, providing an async-friendly API that is similar to the widely used `Requests library <https://requests.readthedocs.io/>`__.
589
590 It offers the following methods:
591
592 ``await datasette.client.get(path, **kwargs)`` - returns HTTPX Response
593 Execute an internal GET request against that path.
594
595 ``await datasette.client.post(path, **kwargs)`` - returns HTTPX Response
596 Execute an internal POST request. Use ``data={"name": "value"}`` to pass form parameters.
597
598 ``await datasette.client.options(path, **kwargs)`` - returns HTTPX Response
599 Execute an internal OPTIONS request.
600
601 ``await datasette.client.head(path, **kwargs)`` - returns HTTPX Response
602 Execute an internal HEAD request.
603
604 ``await datasette.client.put(path, **kwargs)`` - returns HTTPX Response
605 Execute an internal PUT request.
606
607 ``await datasette.client.patch(path, **kwargs)`` - returns HTTPX Response
608 Execute an internal PATCH request.
609
610 ``await datasette.client.delete(path, **kwargs)`` - returns HTTPX Response
611 Execute an internal DELETE request.
612
613 ``await datasette.client.request(method, path, **kwargs)`` - returns HTTPX Response
614 Execute an internal request with the given HTTP method against that path.
615
616 These methods can be used with :ref:`internals_datasette_urls` - for example:
617
618 .. code-block:: python
619
620 table_json = (
621 await datasette.client.get(
622 datasette.urls.table(
623 "fixtures", "facetable", format="json"
624 )
625 )
626 ).json()
627
628 ``datasette.client`` methods automatically take the current :ref:`setting_base_url` setting into account, whether or not you use the ``datasette.urls`` family of methods to construct the path.
629
630 For documentation on available ``**kwargs`` options and the shape of the HTTPX Response object refer to the `HTTPX Async documentation <https://www.python-httpx.org/async/>`__.
631
632 .. _internals_datasette_urls:
633
634 datasette.urls
635 --------------
636
637 The ``datasette.urls`` object contains methods for building URLs to pages within Datasette. Plugins should use this to link to pages, since these methods take into account any :ref:`setting_base_url` configuration setting that might be in effect.
638
639 ``datasette.urls.instance(format=None)``
640 Returns the URL to the Datasette instance root page. This is usually ``"/"``.
641
642 ``datasette.urls.path(path, format=None)``
643 Takes a path and returns the full path, taking ``base_url`` into account.
644
645 For example, ``datasette.urls.path("-/logout")`` will return the path to the logout page, which will be ``"/-/logout"`` by default or ``/prefix-path/-/logout`` if ``base_url`` is set to ``/prefix-path/``
646
647 ``datasette.urls.logout()``
648 Returns the URL to the logout page, usually ``"/-/logout"``
649
650 ``datasette.urls.static(path)``
651 Returns the URL of one of Datasette's default static assets, for example ``"/-/static/app.css"``
652
653 ``datasette.urls.static_plugins(plugin_name, path)``
654 Returns the URL of one of the static assets belonging to a plugin.
655
656 ``datasette.urls.static_plugins("datasette_cluster_map", "datasette-cluster-map.js")`` would return ``"/-/static-plugins/datasette_cluster_map/datasette-cluster-map.js"``
657
658 ``datasette.urls.static(path)``
659 Returns the URL of one of Datasette's default static assets, for example ``"/-/static/app.css"``
660
661 ``datasette.urls.database(database_name, format=None)``
662 Returns the URL to a database page, for example ``"/fixtures"``
663
664 ``datasette.urls.table(database_name, table_name, format=None)``
665 Returns the URL to a table page, for example ``"/fixtures/facetable"``
666
667 ``datasette.urls.query(database_name, query_name, format=None)``
668 Returns the URL to a query page, for example ``"/fixtures/pragma_cache_size"``
669
670 These functions can be accessed via the ``{{ urls }}`` object in Datasette templates, for example:
671
672 .. code-block:: jinja
673
674 <a href="{{ urls.instance() }}">Homepage</a>
675 <a href="{{ urls.database("fixtures") }}">Fixtures database</a>
676 <a href="{{ urls.table("fixtures", "facetable") }}">facetable table</a>
677 <a href="{{ urls.query("fixtures", "pragma_cache_size") }}">pragma_cache_size query</a>
678
679 Use the ``format="json"`` (or ``"csv"`` or other formats supported by plugins) arguments to get back URLs to the JSON representation. This is the path with ``.json`` added on the end.
680
681 These methods each return a ``datasette.utils.PrefixedUrlString`` object, which is a subclass of the Python ``str`` type. This allows the logic that considers the ``base_url`` setting to detect if that prefix has already been applied to the path.
682
683 .. _internals_database:
684
685 Database class
686 ==============
687
688 Instances of the ``Database`` class can be used to execute queries against attached SQLite databases, and to run introspection against their schemas.
689
690 .. _database_constructor:
691
692 Database(ds, path=None, is_mutable=True, is_memory=False, memory_name=None)
693 ---------------------------------------------------------------------------
694
695 The ``Database()`` constructor can be used by plugins, in conjunction with :ref:`datasette_add_database`, to create and register new databases.
696
697 The arguments are as follows:
698
699 ``ds`` - :ref:`internals_datasette` (required)
700 The Datasette instance you are attaching this database to.
701
702 ``path`` - string
703 Path to a SQLite database file on disk.
704
705 ``is_mutable`` - boolean
706 Set this to ``False`` to cause Datasette to open the file in immutable mode.
707
708 ``is_memory`` - boolean
709 Use this to create non-shared memory connections.
710
711 ``memory_name`` - string or ``None``
712 Use this to create a named in-memory database. Unlike regular memory databases these can be accessed by multiple threads and will persist an changes made to them for the lifetime of the Datasette server process.
713
714 The first argument is the ``datasette`` instance you are attaching to, the second is a ``path=``, then ``is_mutable`` and ``is_memory`` are both optional arguments.
715
716 .. _database_hash:
717
718 db.hash
719 -------
720
721 If the database was opened in immutable mode, this property returns the 64 character SHA-256 hash of the database contents as a string. Otherwise it returns ``None``.
722
723 .. _database_execute:
724
725 await db.execute(sql, ...)
726 --------------------------
727
728 Executes a SQL query against the database and returns the resulting rows (see :ref:`database_results`).
729
730 ``sql`` - string (required)
731 The SQL query to execute. This can include ``?`` or ``:named`` parameters.
732
733 ``params`` - list or dict
734 A list or dictionary of values to use for the parameters. List for ``?``, dictionary for ``:named``.
735
736 ``truncate`` - boolean
737 Should the rows returned by the query be truncated at the maximum page size? Defaults to ``True``, set this to ``False`` to disable truncation.
738
739 ``custom_time_limit`` - integer ms
740 A custom time limit for this query. This can be set to a lower value than the Datasette configured default. If a query takes longer than this it will be terminated early and raise a ``dataette.database.QueryInterrupted`` exception.
741
742 ``page_size`` - integer
743 Set a custom page size for truncation, over-riding the configured Datasette default.
744
745 ``log_sql_errors`` - boolean
746 Should any SQL errors be logged to the console in addition to being raised as an error? Defaults to ``True``.
747
748 .. _database_results:
749
750 Results
751 -------
752
753 The ``db.execute()`` method returns a single ``Results`` object. This can be used to access the rows returned by the query.
754
755 Iterating over a ``Results`` object will yield SQLite `Row objects <https://docs.python.org/3/library/sqlite3.html#row-objects>`__. Each of these can be treated as a tuple or can be accessed using ``row["column"]`` syntax:
756
757 .. code-block:: python
758
759 info = []
760 results = await db.execute("select name from sqlite_master")
761 for row in results:
762 info.append(row["name"])
763
764 The ``Results`` object also has the following properties and methods:
765
766 ``.truncated`` - boolean
767 Indicates if this query was truncated - if it returned more results than the specified ``page_size``. If this is true then the results object will only provide access to the first ``page_size`` rows in the query result. You can disable truncation by passing ``truncate=False`` to the ``db.query()`` method.
768
769 ``.columns`` - list of strings
770 A list of column names returned by the query.
771
772 ``.rows`` - list of sqlite3.Row
773 This property provides direct access to the list of rows returned by the database. You can access specific rows by index using ``results.rows[0]``.
774
775 ``.first()`` - row or None
776 Returns the first row in the results, or ``None`` if no rows were returned.
777
778 ``.single_value()``
779 Returns the value of the first column of the first row of results - but only if the query returned a single row with a single column. Raises a ``datasette.database.MultipleValues`` exception otherwise.
780
781 ``.__len__()``
782 Calling ``len(results)`` returns the (truncated) number of returned results.
783
784 .. _database_execute_fn:
785
786 await db.execute_fn(fn)
787 -----------------------
788
789 Executes a given callback function against a read-only database connection running in a thread. The function will be passed a SQLite connection, and the return value from the function will be returned by the ``await``.
790
791 Example usage:
792
793 .. code-block:: python
794
795 def get_version(conn):
796 return conn.execute(
797 "select sqlite_version()"
798 ).fetchall()[0][0]
799
800
801 version = await db.execute_fn(get_version)
802
803 .. _database_execute_write:
804
805 await db.execute_write(sql, params=None, block=True)
806 -----------------------------------------------------
807
808 SQLite only allows one database connection to write at a time. Datasette handles this for you by maintaining a queue of writes to be executed against a given database. Plugins can submit write operations to this queue and they will be executed in the order in which they are received.
809
810 This method can be used to queue up a non-SELECT SQL query to be executed against a single write connection to the database.
811
812 You can pass additional SQL parameters as a tuple or dictionary.
813
814 The method will block until the operation is completed, and the return value will be the return from calling ``conn.execute(...)`` using the underlying ``sqlite3`` Python library.
815
816 If you pass ``block=False`` this behaviour changes to "fire and forget" - queries will be added to the write queue and executed in a separate thread while your code can continue to do other things. The method will return a UUID representing the queued task.
817
818 .. _database_execute_write_script:
819
820 await db.execute_write_script(sql, block=True)
821 -----------------------------------------------
822
823 Like ``execute_write()`` but can be used to send multiple SQL statements in a single string separated by semicolons, using the ``sqlite3`` `conn.executescript() <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.executescript>`__ method.
824
825 .. _database_execute_write_many:
826
827 await db.execute_write_many(sql, params_seq, block=True)
828 ---------------------------------------------------------
829
830 Like ``execute_write()`` but uses the ``sqlite3`` `conn.executemany() <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.executemany>`__ method. This will efficiently execute the same SQL statement against each of the parameters in the ``params_seq`` iterator, for example:
831
832 .. code-block:: python
833
834 await db.execute_write_many(
835 "insert into characters (id, name) values (?, ?)",
836 [(1, "Melanie"), (2, "Selma"), (2, "Viktor")],
837 )
838
839 .. _database_execute_write_fn:
840
841 await db.execute_write_fn(fn, block=True)
842 ------------------------------------------
843
844 This method works like ``.execute_write()``, but instead of a SQL statement you give it a callable Python function. Your function will be queued up and then called when the write connection is available, passing that connection as the argument to the function.
845
846 The function can then perform multiple actions, safe in the knowledge that it has exclusive access to the single writable connection for as long as it is executing.
847
848 .. warning::
849
850 ``fn`` needs to be a regular function, not an ``async def`` function.
851
852 For example:
853
854 .. code-block:: python
855
856 def delete_and_return_count(conn):
857 conn.execute("delete from some_table where id > 5")
858 return conn.execute(
859 "select count(*) from some_table"
860 ).fetchone()[0]
861
862
863 try:
864 num_rows_left = await database.execute_write_fn(
865 delete_and_return_count
866 )
867 except Exception as e:
868 print("An error occurred:", e)
869
870 The value returned from ``await database.execute_write_fn(...)`` will be the return value from your function.
871
872 If your function raises an exception that exception will be propagated up to the ``await`` line.
873
874 If you specify ``block=False`` the method becomes fire-and-forget, queueing your function to be executed and then allowing your code after the call to ``.execute_write_fn()`` to continue running while the underlying thread waits for an opportunity to run your function. A UUID representing the queued task will be returned. Any exceptions in your code will be silently swallowed.
875
876 .. _database_close:
877
878 db.close()
879 ----------
880
881 Closes all of the open connections to file-backed databases. This is mainly intended to be used by large test suites, to avoid hitting limits on the number of open files.
882
883 .. _internals_database_introspection:
884
885 Database introspection
886 ----------------------
887
888 The ``Database`` class also provides properties and methods for introspecting the database.
889
890 ``db.name`` - string
891 The name of the database - usually the filename without the ``.db`` prefix.
892
893 ``db.size`` - integer
894 The size of the database file in bytes. 0 for ``:memory:`` databases.
895
896 ``db.mtime_ns`` - integer or None
897 The last modification time of the database file in nanoseconds since the epoch. ``None`` for ``:memory:`` databases.
898
899 ``db.is_mutable`` - boolean
900 Is this database mutable, and allowed to accept writes?
901
902 ``db.is_memory`` - boolean
903 Is this database an in-memory database?
904
905 ``await db.attached_databases()`` - list of named tuples
906 Returns a list of additional databases that have been connected to this database using the SQLite ATTACH command. Each named tuple has fields ``seq``, ``name`` and ``file``.
907
908 ``await db.table_exists(table)`` - boolean
909 Check if a table called ``table`` exists.
910
911 ``await db.table_names()`` - list of strings
912 List of names of tables in the database.
913
914 ``await db.view_names()`` - list of strings
915 List of names of views in the database.
916
917 ``await db.table_columns(table)`` - list of strings
918 Names of columns in a specific table.
919
920 ``await db.table_column_details(table)`` - list of named tuples
921 Full details of the columns in a specific table. Each column is represented by a ``Column`` named tuple with fields ``cid`` (integer representing the column position), ``name`` (string), ``type`` (string, e.g. ``REAL`` or ``VARCHAR(30)``), ``notnull`` (integer 1 or 0), ``default_value`` (string or None), ``is_pk`` (integer 1 or 0).
922
923 ``await db.primary_keys(table)`` - list of strings
924 Names of the columns that are part of the primary key for this table.
925
926 ``await db.fts_table(table)`` - string or None
927 The name of the FTS table associated with this table, if one exists.
928
929 ``await db.label_column_for_table(table)`` - string or None
930 The label column that is associated with this table - either automatically detected or using the ``"label_column"`` key from :ref:`metadata`, see :ref:`label_columns`.
931
932 ``await db.foreign_keys_for_table(table)`` - list of dictionaries
933 Details of columns in this table which are foreign keys to other tables. A list of dictionaries where each dictionary is shaped like this: ``{"column": string, "other_table": string, "other_column": string}``.
934
935 ``await db.hidden_table_names()`` - list of strings
936 List of tables which Datasette "hides" by default - usually these are tables associated with SQLite's full-text search feature, the SpatiaLite extension or tables hidden using the :ref:`metadata_hiding_tables` feature.
937
938 ``await db.get_table_definition(table)`` - string
939 Returns the SQL definition for the table - the ``CREATE TABLE`` statement and any associated ``CREATE INDEX`` statements.
940
941 ``await db.get_view_definition(view)`` - string
942 Returns the SQL definition of the named view.
943
944 ``await db.get_all_foreign_keys()`` - dictionary
945 Dictionary representing both incoming and outgoing foreign keys for this table. It has two keys, ``"incoming"`` and ``"outgoing"``, each of which is a list of dictionaries with keys ``"column"``, ``"other_table"`` and ``"other_column"``. For example:
946
947 .. code-block:: json
948
949 {
950 "incoming": [],
951 "outgoing": [
952 {
953 "other_table": "attraction_characteristic",
954 "column": "characteristic_id",
955 "other_column": "pk",
956 },
957 {
958 "other_table": "roadside_attractions",
959 "column": "attraction_id",
960 "other_column": "pk",
961 }
962 ]
963 }
964
965
966 .. _internals_csrf:
967
968 CSRF protection
969 ===============
970
971 Datasette uses `asgi-csrf <https://github.com/simonw/asgi-csrf>`__ to guard against CSRF attacks on form POST submissions. Users receive a ``ds_csrftoken`` cookie which is compared against the ``csrftoken`` form field (or ``x-csrftoken`` HTTP header) for every incoming request.
972
973 If your plugin implements a ``<form method="POST">`` anywhere you will need to include that token. You can do so with the following template snippet:
974
975 .. code-block:: html
976
977 <input type="hidden" name="csrftoken" value="{{ csrftoken() }}">
978
979 If you are rendering templates using the :ref:`datasette_render_template` method the ``csrftoken()`` helper will only work if you provide the ``request=`` argument to that method. If you forget to do this you will see the following error::
980
981 form-urlencoded POST field did not match cookie
982
983 You can selectively disable CSRF protection using the :ref:`plugin_hook_skip_csrf` hook.
984
985 .. _internals_internal:
986
987 The _internal database
988 ======================
989
990 .. warning::
991 This API should be considered unstable - the structure of these tables may change prior to the release of Datasette 1.0.
992
993 Datasette maintains an in-memory SQLite database with details of the the databases, tables and columns for all of the attached databases.
994
995 By default all actors are denied access to the ``view-database`` permission for the ``_internal`` database, so the database is not visible to anyone unless they :ref:`sign in as root <authentication_root>`.
996
997 Plugins can access this database by calling ``db = datasette.get_database("_internal")`` and then executing queries using the :ref:`Database API <internals_database>`.
998
999 You can explore an example of this database by `signing in as root <https://latest.datasette.io/login-as-root>`__ to the ``latest.datasette.io`` demo instance and then navigating to `latest.datasette.io/_internal <https://latest.datasette.io/_internal>`__.
1000
1001 .. _internals_utils:
1002
1003 The datasette.utils module
1004 ==========================
1005
1006 The ``datasette.utils`` module contains various utility functions used by Datasette. As a general rule you should consider anything in this module to be unstable - functions and classes here could change without warning or be removed entirely between Datasette releases, without being mentioned in the release notes.
1007
1008 The exception to this rule is anythang that is documented here. If you find a need for an undocumented utility function in your own work, consider `opening an issue <https://github.com/simonw/datasette/issues/new>`__ requesting that the function you are using be upgraded to documented and supported status.
1009
1010 .. _internals_utils_parse_metadata:
1011
1012 parse_metadata(content)
1013 -----------------------
1014
1015 This function accepts a string containing either JSON or YAML, expected to be of the format described in :ref:`metadata`. It returns a nested Python dictionary representing the parsed data from that string.
1016
1017 If the metadata cannot be parsed as either JSON or YAML the function will raise a ``utils.BadMetadataError`` exception.
1018
1019 .. autofunction:: datasette.utils.parse_metadata
1020
1021 .. _internals_utils_await_me_maybe:
1022
1023 await_me_maybe(value)
1024 ---------------------
1025
1026 Utility function for calling ``await`` on a return value if it is awaitable, otherwise returning the value. This is used by Datasette to support plugin hooks that can optionally return awaitable functions. Read more about this function in `The “await me maybe” pattern for Python asyncio <https://simonwillison.net/2020/Sep/2/await-me-maybe/>`__.
1027
1028 .. autofunction:: datasette.utils.await_me_maybe
1029
1030 .. _internals_tilde_encoding:
1031
1032 Tilde encoding
1033 --------------
1034
1035 Datasette uses a custom encoding scheme in some places, called **tilde encoding**. This is primarily used for table names and row primary keys, to avoid any confusion between ``/`` characters in those values and the Datasette URLs that reference them.
1036
1037 Tilde encoding uses the same algorithm as `URL percent-encoding <https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding>`__, but with the ``~`` tilde character used in place of ``%``.
1038
1039 Any character other than ``ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789_-`` will be replaced by the numeric equivalent preceded by a tilde. For example:
1040
1041 - ``/`` becomes ``~2F``
1042 - ``.`` becomes ``~2E``
1043 - ``%`` becomes ``~25``
1044 - ``~`` becomes ``~7E``
1045 - Space becomes ``+``
1046 - ``polls/2022.primary`` becomes ``polls~2F2022~2Eprimary``
1047
1048 Note that the space character is a special case: it will be replaced with a ``+`` symbol.
1049
1050 .. _internals_utils_tilde_encode:
1051
1052 .. autofunction:: datasette.utils.tilde_encode
1053
1054 .. _internals_utils_tilde_decode:
1055
1056 .. autofunction:: datasette.utils.tilde_decode
1057
1058 .. _internals_tracer:
1059
1060 datasette.tracer
1061 ================
1062
1063 Running Datasette with ``--setting trace_debug 1`` enables trace debug output, which can then be viewed by adding ``?_trace=1`` to the query string for any page.
1064
1065 You can see an example of this at the bottom of `latest.datasette.io/fixtures/facetable?_trace=1 <https://latest.datasette.io/fixtures/facetable?_trace=1>`__. The JSON output shows full details of every SQL query that was executed to generate the page.
1066
1067 The `datasette-pretty-traces <https://datasette.io/plugins/datasette-pretty-traces>`__ plugin can be installed to provide a more readable display of this information. You can see `a demo of that here <https://latest-with-plugins.datasette.io/github/commits?_trace=1>`__.
1068
1069 You can add your own custom traces to the JSON output using the ``trace()`` context manager. This takes a string that identifies the type of trace being recorded, and records any keyword arguments as additional JSON keys on the resulting trace object.
1070
1071 The start and end time, duration and a traceback of where the trace was executed will be automatically attached to the JSON object.
1072
1073 This example uses trace to record the start, end and duration of any HTTP GET requests made using the function:
1074
1075 .. code-block:: python
1076
1077 from datasette.tracer import trace
1078 import httpx
1079
1080
1081 async def fetch_url(url):
1082 with trace("fetch-url", url=url):
1083 async with httpx.AsyncClient() as client:
1084 return await client.get(url)
1085
1086 .. _internals_tracer_trace_child_tasks:
1087
1088 Tracing child tasks
1089 -------------------
1090
1091 If your code uses a mechanism such as ``asyncio.gather()`` to execute code in additional tasks you may find that some of the traces are missing from the display.
1092
1093 You can use the ``trace_child_tasks()`` context manager to ensure these child tasks are correctly handled.
1094
1095 .. code-block:: python
1096
1097 from datasette import tracer
1098
1099 with tracer.trace_child_tasks():
1100 results = await asyncio.gather(
1101 # ... async tasks here
1102 )
1103
1104 This example uses the :ref:`register_routes() <plugin_register_routes>` plugin hook to add a page at ``/parallel-queries`` which executes two SQL queries in parallel using ``asyncio.gather()`` and returns their results.
1105
1106 .. code-block:: python
1107
1108 from datasette import hookimpl
1109 from datasette import tracer
1110
1111
1112 @hookimpl
1113 def register_routes():
1114 async def parallel_queries(datasette):
1115 db = datasette.get_database()
1116 with tracer.trace_child_tasks():
1117 one, two = await asyncio.gather(
1118 db.execute("select 1"),
1119 db.execute("select 2"),
1120 )
1121 return Response.json(
1122 {
1123 "one": one.single_value(),
1124 "two": two.single_value(),
1125 }
1126 )
1127
1128 return [
1129 (r"/parallel-queries$", parallel_queries),
1130 ]
1131
1132
1133 Adding ``?_trace=1`` will show that the trace covers both of those child tasks.
1134
1135 .. _internals_shortcuts:
1136
1137 Import shortcuts
1138 ================
1139
1140 The following commonly used symbols can be imported directly from the ``datasette`` module:
1141
1142 .. code-block:: python
1143
1144 from datasette import Response
1145 from datasette import Forbidden
1146 from datasette import NotFound
1147 from datasette import hookimpl
1148 from datasette import actor_matches_allow