-
-
Notifications
You must be signed in to change notification settings - Fork 813
Description
Datasette views currently work by creating a set of data that should be returned as JSON, then defining an additional, optional template_data() function which is called if the view is being rendered as HTML.
This template_data() function calculates extra template context variables which are necessary for the HTML view but should not be included in the JSON.
Example of how that is used today:
datasette/datasette/views/table.py
Lines 672 to 704 in 2b79f2b
| async def template_data(): | |
| display_columns, display_rows = await self.display_columns_and_rows( | |
| name, | |
| table, | |
| description, | |
| rows, | |
| link_column=False, | |
| expand_foreign_keys=True, | |
| ) | |
| for column in display_columns: | |
| column["sortable"] = False | |
| return { | |
| "database_hash": hash, | |
| "foreign_key_tables": await self.foreign_key_tables( | |
| name, table, pk_values | |
| ), | |
| "display_columns": display_columns, | |
| "display_rows": display_rows, | |
| "custom_rows_and_columns_templates": [ | |
| "_rows_and_columns-{}-{}.html".format( | |
| to_css_class(name), to_css_class(table) | |
| ), | |
| "_rows_and_columns-row-{}-{}.html".format( | |
| to_css_class(name), to_css_class(table) | |
| ), | |
| "_rows_and_columns.html", | |
| ], | |
| "metadata": self.ds.metadata.get("databases", {}).get(name, {}).get( | |
| "tables", {} | |
| ).get( | |
| table, {} | |
| ), | |
| } |
With features like Facets in #255 I'm beginning to want to move more items into the template_data() - in the case of facets it's the suggested_facets array. This saves that feature from being calculated (involving several SQL queries) for the JSON case where it is unlikely to be used.
But... as an API user, I want to still optionally be able to access that information.
Solution: Add a ?_extra=suggested_facets&_extra=table_metadata argument which can be used to optionally request additional blocks to be added to the JSON API.
Then redefine as many of the current template_data() features as extra arguments instead, and teach Datasette to return certain extras by default when rendering templates.
This could allow the JSON representation to be slimmed down further (removing e.g. the table_definition and view_definition keys) while still making that information available to API users who need it.