Skip to content

Commit defca32

Browse files
claudesimonw
authored andcommitted
Export dialog groups formats that can stream with TSV and CSV
Plugin output formats that accept row_stream now share the form used by TSV and CSV, so the "Include all rows" and "Expand labels" options apply to them. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016Bvfq9SBhxPegj4hvi5NF4
1 parent ad3103b commit defca32

7 files changed

Lines changed: 131 additions & 23 deletions

File tree

‎datasette/app.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2668,6 +2668,8 @@ def _register_renderers(self):
26682668
"description": renderer.get("description"),
26692669
"is_binary": is_binary,
26702670
"is_webpage": is_webpage,
2671+
# Formats that can stream are grouped with "Include all rows"
2672+
"can_stream": self._renderer_can_stream[extension],
26712673
}
26722674

26732675
async def render_template(

‎datasette/static/export-dialog.js‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,9 @@
7171
errorFor(el)?.remove();
7272
}
7373

74-
// TSV and CSV build their URLs from the form they share, so its checkboxes
75-
// apply. TSV's buttons send the form to its own path using formaction.
74+
// TSV, CSV and plugin formats that can stream build their URLs from the
75+
// form they share, so its checkboxes apply. All but CSV send the form to
76+
// their own path using formaction.
7677
function exportUrl(el) {
7778
const row = el.closest(".export-option");
7879
const form = el.closest(".export-csv-form");
@@ -82,8 +83,11 @@
8283
const link = row.querySelector("a.export-action[href]");
8384
return new URL(link.getAttribute("href"), location.href).href;
8485
}
85-
const view = row.querySelector('[data-export-action="view"]');
86-
const path = view.getAttribute("formaction") || form.getAttribute("action");
86+
// Binary formats have no View button, so look at Download as well
87+
const submit = row.querySelector("[formaction]");
88+
const path = submit
89+
? submit.getAttribute("formaction")
90+
: form.getAttribute("action");
8791
const url = new URL(path, location.href);
8892
// Row pages have no fields to send, so no "?" either
8993
url.search = new URLSearchParams(new FormData(form));
@@ -164,8 +168,8 @@
164168
const rowsText = (n) => `${formatNumber(n)} row${n === 1 ? "" : "s"}`;
165169

166170
// How many rows an export returns: JSON and plugin formats return the rows
167-
// on this page, TSV and CSV ("csv" here) ask for _size=max starting from
168-
// this page, and "Include all rows" streams every row from the first one.
171+
// on this page, the formats that can stream - TSV, CSV and some plugin
172+
// formats, "csv" here - ask for _size=max starting from this page, and "Include all rows" streams every row from the first one.
169173
// Mirrors the rows_label macro in _export_dialog.html.
170174
function rowsLabel(kind, rows, stream) {
171175
const { page, more, later, max, total } = rows;
@@ -222,7 +226,7 @@
222226
rows.total !== null &&
223227
rows.total <= rows.max
224228
) {
225-
// TSV and CSV already include every row, so the option would do nothing
229+
// Those formats already include every row, so the option would do nothing
226230
stream.checked = false;
227231
stream.disabled = true;
228232
stream.closest("label").hidden = true;
@@ -328,7 +332,7 @@
328332
const el = ev.target.closest("[data-export-action]");
329333
const action = el && el.dataset.exportAction;
330334
if (action === "download" && el.closest(".export-csv-form")) {
331-
// Download TSV or CSV through a link with a download attribute, like
335+
// Download these formats through a link with a download attribute, like
332336
// the other formats, rather than submitting the form with _dl=on:
333337
// WebKit on Linux does not treat that response as a download
334338
ev.preventDefault();

‎datasette/templates/_export_dialog.html‎

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,29 @@
1212
that one row. Otherwise the dialog also offers more JSON shapes, using
1313
urls.modify().
1414
Formats from plugins use renderer_options for their label, description
15-
and which actions to offer. -#}
15+
and which actions to offer. Those that can stream every row are grouped
16+
with TSV and CSV, so that "Include all rows" applies to them. -#}
1617
{% set export_base = export_meta or "data" %}
1718
{% set export_later = export_rows.later if export_rows else false %}
1819
{#- "Include all rows" streams every row from the first one, so offer it on
1920
every later page, and on the first page when CSV would stop short -#}
2021
{% set csv_stream = export_rows and display_rows and (export_later or (next_url and not (export_rows.total is not none and export_rows.total <= export_rows.max))) and settings.default_allow_stream %}
22+
{#- Formats from plugins that can stream, as (extension, path, options) -#}
23+
{% set streaming = namespace(formats=[], names=(["TSV"] if url_tsv_path else []) + ["CSV"]) %}
24+
{% if display_rows %}
25+
{% for name, url in renderers.items() if name not in ("json", "csv") and not (name == "tsv" and url_tsv_path) %}
26+
{% set options = (renderer_options or {}).get(name) or {} %}
27+
{% if options.can_stream %}
28+
{% set streaming.formats = streaming.formats + [(name, url.split("?")[0], options)] %}
29+
{% set streaming.names = streaming.names + [options.label or name] %}
30+
{% endif %}
31+
{% endfor %}
32+
{% endif %}
33+
{% set streaming_extensions = streaming.formats|map("first")|list %}
2134
{% macro rows_text(n) %}{{ "{:,}".format(n) }} row{{ "" if n == 1 else "s" }}{% endmacro %}
2235
{#- How many rows an export returns. JSON and plugin formats return the rows
23-
on this page; TSV and CSV ask for _size=max, starting from this page.
36+
on this page; TSV, CSV and plugin formats that can stream ("csv" here)
37+
ask for _size=max, starting from this page.
2438
Mirrored by rowsLabel() in export-dialog.js. -#}
2539
{% macro rows_label(kind, rows, id) %}
2640
{%- set n = rows.page -%}
@@ -41,20 +55,22 @@
4155
{%- else -%}First {{ rows_text(n) }}{%- endif -%}
4256
</span>
4357
{%- endmacro %}
44-
{#- TSV or CSV: submit buttons for the shared form, with TSV using formaction -#}
45-
{% macro delimited_option(id, name, description, rows, formaction=none) %}
46-
<div class="export-option" data-export-format="{{ id }}">
58+
{#- TSV, CSV or a plugin format that can stream: submit buttons for the shared
59+
form, with every format other than CSV using formaction. kind is as for
60+
export_option below. -#}
61+
{% macro delimited_option(id, name, description, rows, formaction=none, kind=none) %}
62+
<div class="export-option" data-export-format="{{ id }}"{% if kind %} data-export-kind="{{ kind }}"{% endif %}>
4763
<div class="export-option-text">
4864
<div class="export-option-heading">
4965
<span class="export-option-name" id="export-{{ id }}-name">{{ name }}</span>
5066
{% if rows %}{{ rows_label("csv", rows, id) }}{% endif %}
5167
</div>
52-
<span class="export-option-description">{{ description }}</span>
68+
{% if description %}<span class="export-option-description">{{ description }}</span>{% endif %}
5369
</div>
5470
<div class="export-actions" role="group" aria-labelledby="export-{{ id }}-name"{% if rows %} aria-describedby="export-{{ id }}-rows"{% endif %}>
55-
<button type="button" class="export-action" data-export-action="copy" hidden>Copy</button>
56-
<button type="submit" class="export-action" data-export-action="view"{% if formaction %} formaction="{{ formaction }}"{% endif %}>View</button>
57-
<button type="submit" class="export-action" data-export-action="download" name="_dl" value="on"{% if formaction %} formaction="{{ formaction }}"{% endif %}>Download</button>
71+
{% if not kind %}<button type="button" class="export-action" data-export-action="copy" hidden>Copy</button>{% endif %}
72+
{% if kind != "binary" %}<button type="submit" class="export-action" data-export-action="view"{% if formaction %} formaction="{{ formaction }}"{% endif %}>View</button>{% endif %}
73+
{% if kind != "webpage" %}<button type="submit" class="export-action" data-export-action="download" name="_dl" value="on"{% if formaction %} formaction="{{ formaction }}"{% endif %}>Download</button>{% endif %}
5874
<button type="button" class="export-action" data-export-action="copy-url" hidden>Copy URL</button>
5975
</div>
6076
</div>
@@ -89,15 +105,18 @@ <h2 class="modal-title" id="export-dialog-title">Export data</h2>
89105
</div>
90106
<div class="modal-body export-links">
91107
{% if export_scope %}<p class="export-scope" id="export-scope" title="{{ export_scope }}{% if export_scope_description %} {{ export_scope_description }}{% endif %}"><strong>{{ export_scope }}</strong>{% if export_scope_description %} {{ export_scope_description }}{% endif %}</p>{% endif %}
92-
{% if export_later %}<p class="export-page-note" id="export-page-note">These exports start from this page, not the first page.{% if csv_stream %} Check “Include all rows” to export every row as {{ "TSV or " if url_tsv_path }}CSV.{% endif %}</p>{% endif %}
108+
{% if export_later %}<p class="export-page-note" id="export-page-note">These exports start from this page, not the first page.{% if csv_stream %} Check “Include all rows” to export every row as {{ streaming.names[:-1]|join(", ") }}{{ " or " if streaming.names|length > 1 }}{{ streaming.names[-1] }}.{% endif %}</p>{% endif %}
93109
{% if display_rows %}
94-
{#- TSV and CSV share a form, so the options under them apply to both.
95-
The other formats are in a separate box below, as the options do
96-
not apply to them. -#}
110+
{#- TSV, CSV and plugin formats that can stream share a form, so the
111+
options under them apply to them all. The other formats are in a
112+
separate box below, as the options do not apply to them. -#}
97113
<div class="export-options export-option-group">
98114
<form class="export-csv-form" action="{{ url_csv_path }}" method="get">
99115
{% if url_tsv_path %}{{ delimited_option("tsv", "TSV", "Tab-separated values, for pasting into Excel or Google Sheets", export_rows, formaction=url_tsv_path) }}{% endif %}
100116
{{ delimited_option("csv", "CSV", "Comma-separated values, for spreadsheets and other tools", export_rows) }}
117+
{% for name, path, options in streaming.formats %}
118+
{{ delimited_option(name, options.label or name, options.description, export_rows, formaction=path, kind="binary" if options.is_binary else ("webpage" if options.is_webpage else none)) }}
119+
{% endfor %}
101120
{% if expandable_columns or csv_stream %}
102121
<div class="export-csv-options">
103122
{% if expandable_columns %}<label><input type="checkbox" name="_labels" checked> Expand labels</label>{% endif %}
@@ -121,7 +140,7 @@ <h2 class="modal-title" id="export-dialog-title">Export data</h2>
121140
{{ export_option("json-object", "JSON object", "Rows keyed by their primary key", urls.modify(renderers['json'], add={'_shape': 'object'}), export_base ~ ".json", export_rows) }}
122141
{% endif %}
123142
{% endif %}
124-
{% for name, url in renderers.items() if name not in ("json", "csv") and not (name == "tsv" and url_tsv_path) %}
143+
{% for name, url in renderers.items() if name not in ("json", "csv") and not (name == "tsv" and url_tsv_path) and name not in streaming_extensions %}
125144
{% set options = (renderer_options or {}).get(name) or {} %}
126145
{{ export_option("format-" ~ loop.index, options.label or name, options.description, url, export_base ~ "." ~ name, export_rows, kind="binary" if options.is_binary else ("webpage" if options.is_webpage else none)) }}
127146
{% endfor %}

‎docs/changelog.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Unreleased
3535
- **Backwards incompatible:** the ``format_bytes()`` function is no longer available in templates, and ``datasette.utils.format_bytes()`` has been removed. Custom templates that call ``{{ format_bytes(size) }}`` should use Jinja's built-in `filesizeformat <https://jinja.palletsprojects.com/en/stable/templates/#jinja-filters.filesizeformat>`__ filter instead: ``{{ size|filesizeformat }}``. (:issue:`1841`)
3636
- File sizes shown on the database page and in the tooltips for binary values now use decimal units, where 1 MB is 1,000,000 bytes, matching the sizes already shown on the homepage. They previously used 1 MB to mean 1,048,576 bytes, so a 5,242,880 byte database that was displayed as ``5.0 MB`` is now displayed as ``5.2 MB``.
3737
- ``?_stream=1`` now fetches rows in pages of :ref:`setting_max_returned_rows`, 1,000 by default, instead of the default page size of 100. This makes streaming every row of a large table several times faster. A ``?_size=`` in the URL is still respected.
38+
- The "Export data" dialog now groups plugin formats that can stream with TSV and CSV, so its "Include all rows" option applies to those formats too.
3839

3940
- New ``datasette.urls.modify(target, add=, replace=, remove=, format=)`` method for building links that change the query string of the current page or of any other path. It applies ``base_url`` for you and is available in templates as ``urls.modify()``. See :ref:`internals_datasette_urls_modify`. (:issue:`1342`)
4041
- Fixed a bug where sort, facet and filter-removal links on the table page dropped query string arguments with blank values, so sorting ``/db/table?name=`` lost the filter for rows where ``name`` is the empty string.

‎docs/csv_export.rst‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ Options
6060
-------
6161

6262
TSV and CSV share the following options. These are only offered for tables
63-
and views:
63+
and views. Formats added by plugins that can
64+
:ref:`stream every row <plugin_register_output_renderer_streaming>` are listed
65+
alongside TSV and CSV, and these options apply to them as well:
6466

6567
* **expand labels** - if your table has any foreign key references this option
6668
will cause the export to gain additional ``COLUMN_NAME_label`` columns with a

‎docs/plugin_hooks.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,8 @@ A table can have far more rows than fit on one page. A ``"render"`` function tha
771771

772772
Use ``async for rows in row_stream.pages()`` to receive a list of rows for each page instead of one row at a time. When streaming every row those pages are :ref:`setting_max_returned_rows` rows each, unless the URL sets a different ``?_size=``.
773773

774+
The :ref:`Export data dialog <csv_export>` lists formats that accept ``row_stream`` in the same group as TSV and CSV, so that its "Include all rows" and "Expand labels" options apply to them. Like TSV and CSV, their links in the dialog use ``?_size=max``.
775+
774776
Datasette's own :ref:`CSV and TSV export <csv_export>` is implemented this way. Some things to be aware of:
775777

776778
- ``?_stream=1`` is ignored by formats that do not accept ``row_stream``.

‎tests/test_renderer_streaming.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,3 +318,81 @@ async def test_row_stream_pages_are_max_returned_rows(plugin):
318318
assert response.text.split() == ["15", "15", "5"]
319319
finally:
320320
ds.close()
321+
322+
323+
@pytest.mark.asyncio
324+
async def test_export_dialog_groups_formats_that_can_stream(ds):
325+
from bs4 import BeautifulSoup
326+
327+
# A later page, so "Include all rows" is offered for this small table
328+
response = await ds.client.get("/data/numbers?_next=10")
329+
dialog = BeautifulSoup(response.text, "html.parser").select_one("#export-dialog")
330+
form = dialog.select_one("form.export-csv-form")
331+
# Formats that accept row_stream share the form with TSV and CSV, so
332+
# "Include all rows" applies to them
333+
formats = [row["data-export-format"] for row in form.select(".export-option")]
334+
assert formats[:2] == ["tsv", "csv"]
335+
assert sorted(formats[2:]) == ["big", "ndjson", "pagesizes"]
336+
assert form.select_one("input[name=_stream]") is not None
337+
ndjson = form.select_one('[data-export-format="ndjson"]')
338+
assert {
339+
button["data-export-action"]: (button["type"], button.get("formaction"))
340+
for button in ndjson.select("button")
341+
} == {
342+
"copy": ("button", None),
343+
"view": ("submit", "/data/numbers.ndjson"),
344+
"download": ("submit", "/data/numbers.ndjson"),
345+
"copy-url": ("button", None),
346+
}
347+
# They return up to max_returned_rows rows, like CSV
348+
assert ndjson.select_one(".export-rows")["data-export-rows"] == "csv"
349+
# Formats that cannot stream stay in the list below, as links
350+
other = dialog.select_one("ul.export-options")
351+
assert other.select_one('a[href^="/data/numbers.notstreaming"]') is not None
352+
assert other.select_one('a[href^="/data/numbers.ndjson"]') is None
353+
assert form.select_one('[formaction="/data/numbers.notstreaming"]') is None
354+
355+
356+
@pytest.mark.asyncio
357+
async def test_export_dialog_binary_format_that_can_stream(ds):
358+
from bs4 import BeautifulSoup
359+
360+
def render_binary(row_stream):
361+
async def body():
362+
async for row in row_stream:
363+
yield bytes([row["id"]])
364+
365+
return Response.stream(body(), content_type="application/octet-stream")
366+
367+
class BinaryPlugin:
368+
__name__ = "BinaryPlugin"
369+
370+
@hookimpl
371+
def register_output_renderer(self):
372+
return {
373+
"extension": "bin",
374+
"render": render_binary,
375+
"label": "Binary",
376+
"is_binary": True,
377+
}
378+
379+
pm.register(BinaryPlugin(), name="binary_renderer")
380+
try:
381+
binary_ds = _make_datasette()
382+
await _add_numbers(binary_ds)
383+
response = await binary_ds.client.get("/data/numbers?_next=10")
384+
binary_ds.close()
385+
finally:
386+
pm.unregister(name="binary_renderer")
387+
dialog = BeautifulSoup(response.text, "html.parser").select_one("#export-dialog")
388+
row = dialog.select_one('form.export-csv-form [data-export-format="bin"]')
389+
assert row["data-export-kind"] == "binary"
390+
# Binary formats offer Download and Copy URL, not Copy or View
391+
assert [
392+
(button["data-export-action"], button.get("formaction"))
393+
for button in row.select("button")
394+
] == [("download", "/data/numbers.bin"), ("copy-url", None)]
395+
assert row.select_one(".export-option-name").text == "Binary"
396+
note = dialog.select_one("#export-page-note").text
397+
assert "to export every row as TSV, CSV, " in note
398+
assert "Binary" in note

0 commit comments

Comments
 (0)