用于在模板中执行 SQL 查询的 Datasette 插件。
datasette.io 广泛使用此插件以及 自定义页面模板,请查看 simonw/datasette.io 以了解其工作原理。
www.niche-museums.com 使用此插件在 Datasette 之上运行一个自定义主题网站。该站点的完整源代码 在此处 - 另请参阅 niche-museums.com,由 Datasette 提供支持。
simonw/til 是另一个简单示例,在 使用由 GitHub Actions 提供支持的自重写 README 来跟踪 TILs 中进行了描述。
运行此命令可在与 Datasette 相同的环境中安装此插件
$ pip install datasette-template-sql
此插件提供了一个新函数,sql(sql_query)
,可在你的 Datasette 模板中使用。
你可以像这样使用它
{% endfor %} {% endfor %}">
{% for row in sql("select 1 + 1 as two, 2 * 4 as eight") %} {% for key in row.keys() %} {{ key }}: {{ row[key] }}<br> {% endfor %} {% endfor %}
此插件将在页面的当前数据库中执行 SQL 查询,在 database.html
、table.html
和 row.html
模板中。如果模板没有当前数据库(例如 index.html
),查询将针对第一个附加的数据库执行。
你可以使用 ?
或 :name
参数语法构建 SQL 查询,通过将列表或字典作为第二个参数传递。
{{ row.topic }}
- {% for til in sql("select * from til where topic = ?", [row.topic]) %}
- {{ til.title }} - {{ til.created[:10] }} {% endfor %}
{% for row in sql("select distinct topic from til order by topic") %} <h2>{{ row.topic }}h2> <ul> {% for til in sql("select * from til where topic = ?", [row.topic]) %} <li><a href="{{ til.url }}">{{ til.title }}a> - {{ til.created[:10] }}li> {% endfor %} ul> {% endfor %}
这是使用 :topic
参数风格的相同示例
{{ row.topic }}
- {% for til in sql("select * from til where topic = :topic", {"topic": row.topic}) %}
- {{ til.title }} - {{ til.created[:10] }} {% endfor %}
{% for row in sql("select distinct topic from til order by topic") %} <h2>{{ row.topic }}h2> <ul> {% for til in sql("select * from til where topic = :topic", {"topic": row.topic}) %} <li><a href="{{ til.url }}">{{ til.title }}a> - {{ til.created[:10] }}li> {% endfor %} ul> {% endfor %}
你可以传递一个可选的 database=
参数来指定用于查询的命名数据库。 例如,如果你附加了一个 news.db
数据库,你可以这样使用:
{{ article.headline }}
{{ article.date }}
{{ article.summary }}
{% endfor %}">{% for article in sql( "select headline, date, summary from articles order by date desc limit 5", database="news" ) %} <h3>{{ article.headline }}h2> <p class="date">{{ article.date }}p> <p>{{ article.summary }}p> {% endfor %}