Better async template function example

pull/635/head
Simon Willison 2019-11-14 15:12:34 -08:00
rodzic 9b381458ea
commit 0e8f8be1db
1 zmienionych plików z 6 dodań i 13 usunięć

Wyświetl plik

@ -643,26 +643,19 @@ Here's an example plugin that returns an authentication object from the ASGI sco
"auth": request.scope.get("auth") "auth": request.scope.get("auth")
} }
And here's an example which adds a ``query_database(sql)`` function which executes a SQL statement and returns the first column of the row: 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:
.. code-block:: python .. code-block:: python
@hookimpl @hookimpl
def extra_template_vars(datasette): def extra_template_vars(datasette, database):
async def sql_first(sql, dbname=None):
async def query_database(sql): dbname = dbname or database or next(iter(datasette.databases.keys()))
first_db = list(datasette.databases.keys())[0] return (await datasette.execute(dbname, sql)).rows[0][0]
return (
await datasette.execute(first_db, sql)
).rows[0][0]
return {
"query_database": query_database,
}
You can then use the new function in a template like so:: You can then use the new function in a template like so::
{{ query_database("select sqlite_version()") }} SQLite version: {{ sql_first("select sqlite_version()") }}
.. _plugin_register_output_renderer: .. _plugin_register_output_renderer: