Skip to content

Commit 7ed0aeb

Browse files
committed
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 c0615b1 commit 7ed0aeb

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
@@ -2674,6 +2674,8 @@ def _register_renderers(self):
26742674
"description": renderer.get("description"),
26752675
"is_binary": is_binary,
26762676
"is_webpage": is_webpage,
2677+
# Formats that can stream are grouped with "Include all rows"
2678+
"can_stream": self._renderer_can_stream[extension],
26772679
}
26782680

26792681
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
append_querystring.
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.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", append_querystring(renderers['json'], '_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
@@ -12,6 +12,7 @@ Unreleased
1212
- New ``Response.stream(body)`` method for returning a response a chunk at a time from an async iterator of strings or bytes, for example from a :ref:`plugin_register_routes` view. See :ref:`internals_response_stream`.
1313
- Output renderers can now stream every row of a table or view. A ``render`` function that accepts the new ``row_stream`` argument - an async iterator of rows - and returns ``Response.stream()`` will be sent every row when the URL includes ``?_stream=1``. See :ref:`plugin_register_output_renderer_streaming`. (:issue:`1101`)
1414
- ``?_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.
15+
- 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.
1516
- CSV and TSV export are now implemented as default output renderers using that mechanism, replacing the previous special case. Plugins can replace either of them by registering a renderer for the ``csv`` or ``tsv`` extension. (:issue:`1062`)
1617
- **Breaking change**: an "include all rows" export that fails part of the way through, or that reaches the :ref:`setting_max_stream_mb` limit, now drops the connection so the download fails. Previously the error message was written as the last line of the file, which otherwise looked complete.
1718
- The ``allow_csv_stream`` and ``max_csv_mb`` settings have been renamed to :ref:`setting_allow_stream` and :ref:`setting_max_stream_mb`, since they now apply to every format that can stream. The previous names continue to work.

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

0 commit comments

Comments
 (0)