From 164b0abcd168fd1c9aa7d74991c1f15c90a37735 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:45:38 +0000 Subject: [PATCH 01/10] Response.stream() for streaming responses from an async iterator Response.stream(body) sends strings or bytes yielded by an async iterator to the client a chunk at a time. It works anywhere a Response does, including views registered using register_routes(). If the iterator fails after the response has started Datasette can no longer send an error page, so the exception is re-raised and the server drops the connection. The client sees a failed request, not a truncated response that looks complete. The iterator is closed if the client disconnects. Refs #2936, #1101 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 42 ++++--- datasette/utils/asgi.py | 50 ++++++++ docs/changelog.rst | 1 + docs/internals.rst | 45 +++++++ tests/test_internals_response.py | 205 +++++++++++++++++++++++++++++++ 5 files changed, 329 insertions(+), 14 deletions(-) diff --git a/datasette/app.py b/datasette/app.py index 3f41d28dfb..17db4439c7 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -3336,26 +3336,40 @@ async def send(message): new_scope = dict(scope, url_route={"kwargs": match.groupdict()}) request.scope = new_scope + response_started = False + + async def tracking_send(message): + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + try: response = await view(request, send) if response: self.ds._write_messages_to_response(request, response) - await response.asgi_send(send) + await response.asgi_send(tracking_send) return - except NotFound as exception: - return await self.handle_404(request, send, exception) - except Forbidden as exception: - # Try the forbidden() plugin hook - for custom_response in pm.hook.forbidden( - datasette=self.ds, request=request, message=exception.args[0] - ): - custom_response = await await_me_maybe(custom_response) - assert ( - custom_response - ), "Default forbidden() hook should have been called" - return await custom_response.asgi_send(send) - except Exception as exception: # noqa: BLE001 + except Exception as exception: # This IS the top-level error handler - it must catch everything + if response_started: + # A streaming response failed part way through. It is too + # late to send an error page, so re-raise and let the server + # drop the connection: the client then sees a failed + # response, not a truncated one that looks complete. + raise + if isinstance(exception, NotFound): + return await self.handle_404(request, send, exception) + if isinstance(exception, Forbidden): + # Try the forbidden() plugin hook + for custom_response in pm.hook.forbidden( + datasette=self.ds, request=request, message=exception.args[0] + ): + custom_response = await await_me_maybe(custom_response) + assert ( + custom_response + ), "Default forbidden() hook should have been called" + return await custom_response.asgi_send(send) return await self.handle_exception(request, send, exception) async def handle_401(self, request, send, exception): diff --git a/datasette/utils/asgi.py b/datasette/utils/asgi.py index 2a26d3875c..2e09137974 100644 --- a/datasette/utils/asgi.py +++ b/datasette/utils/asgi.py @@ -562,10 +562,39 @@ async def asgi_send(self, send): } ) body = self.body + if hasattr(body, "__aiter__"): + await self._asgi_send_stream(body, send) + return if not isinstance(body, bytes): body = body.encode("utf-8") await send({"type": "http.response.body", "body": body}) + async def _asgi_send_stream(self, body, send): + # An exception raised here - by the iterator, or by send() if the + # client has gone away - propagates without the final empty chunk, + # so the server drops the connection and the client can tell that + # the response is incomplete. + iterator = body.__aiter__() + try: + async for chunk in iterator: + if isinstance(chunk, str): + chunk = chunk.encode("utf-8") + if chunk: + await send( + { + "type": "http.response.body", + "body": chunk, + "more_body": True, + } + ) + finally: + # Runs the finally: blocks of an async generator that did not + # finish, for example because the client disconnected + aclose = getattr(iterator, "aclose", None) + if aclose is not None: + await aclose() + await send({"type": "http.response.body", "body": b""}) + def set_cookie( self, key, @@ -624,6 +653,27 @@ def json(cls, body, status=200, headers=None, default=None): content_type="application/json; charset=utf-8", ) + @classmethod + def stream( + cls, + body, + status=200, + headers=None, + content_type="text/plain; charset=utf-8", + ): + """ + A response that is sent to the client a chunk at a time. + + body is an async iterator - usually an async generator - yielding + strings or bytes. Strings are encoded as UTF-8. + """ + if not hasattr(body, "__aiter__"): + raise TypeError( + "Response.stream() body must be an async iterator, " + "such as an async generator" + ) + return cls(body, status=status, headers=headers, content_type=content_type) + @classmethod def error(cls, messages, status=400, headers=None): """ diff --git a/docs/changelog.rst b/docs/changelog.rst index 2346beab5c..fc31a1b45c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,7 @@ Changelog Unreleased ---------- +- 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`. - The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests. - Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ```` element for that name matched a class used by Datasette's own CSS and JavaScript. diff --git a/docs/internals.rst b/docs/internals.rst index 997c4df6e1..bb773489e8 100644 --- a/docs/internals.rst +++ b/docs/internals.rst @@ -308,6 +308,51 @@ Each of the helper methods take optional ``status=`` and ``headers=`` arguments, ``Response.error(messages, status=400)`` returns a JSON error in the :ref:`standard Datasette error format `. ``messages`` can be a single string or a list of strings. Use this for JSON-only endpoints; if your error should content-negotiate between JSON and HTML, raise ``Forbidden``, ``NotFound``, ``BadRequest`` or ``DatasetteError`` instead and Datasette's error handling will build the appropriate response. +.. _internals_response_stream: + +Streaming responses with Response.stream() +------------------------------------------ + +Use ``Response.stream(body)`` to send a response a piece at a time, without first building all of it in memory. This is useful for large exports, and for responses that take a long time to generate. + +``body`` is an async iterator - usually an async generator - that yields strings or bytes. Strings are encoded as UTF-8. + +.. code-block:: python + + from datasette.utils.asgi import Response + + + async def all_rows(datasette, request): + db = datasette.get_database() + + async def body(): + last_id = 0 + while True: + rows = ( + await db.execute( + "select id, name from items where id > ? order by id limit 100", + [last_id], + ) + ).rows + if not rows: + break + for row in rows: + yield f"{row['id']}\t{row['name']}\n" + last_id = rows[-1]["id"] + + return Response.stream( + body(), + content_type="text/tab-separated-values; charset=utf-8", + ) + +``Response.stream()`` also accepts the optional ``status=`` and ``headers=`` arguments. ``content_type=`` defaults to ``text/plain; charset=utf-8``. ``response.set_cookie()`` works as it does for any other response. + +Three things to keep in mind when streaming: + +- The status and headers are sent before the first chunk, so they cannot depend on anything the iterator works out later. Code that might fail in a way the client should see as an error - checking permissions, validating arguments, running the first query - should run in the view function before it returns the response, where raising an exception still produces a regular error page. +- If the iterator raises an exception part way through, Datasette cannot send an error page because the response has already started. The exception is passed on to the server, which drops the connection without completing the response, so the client sees a failed request instead of a truncated response that looks complete. +- If the client disconnects, Datasette closes the iterator. For an async generator this runs any ``finally:`` blocks, which is the place to release resources. + .. _internals_response_asgi_send: Returning a response with .asgi_send(send) diff --git a/tests/test_internals_response.py b/tests/test_internals_response.py index aa3e1ae221..a58f0c8af1 100644 --- a/tests/test_internals_response.py +++ b/tests/test_internals_response.py @@ -2,6 +2,9 @@ import pytest +from datasette import hookimpl +from datasette.app import Datasette +from datasette.plugins import pm from datasette.utils.asgi import Response @@ -78,3 +81,205 @@ def test_response_error_message_list_and_default_status(): "errors": ["First problem", "Second problem"], "status": 400, } + + +async def _collect(response): + events = [] + + async def send(event): + events.append(event) + + await response.asgi_send(send) + return events + + +@pytest.mark.asyncio +async def test_response_stream(): + async def body(): + yield "one\n" + yield b"two\n" + # Empty chunks are skipped - an empty body would end the response + yield "" + yield "café\n" + + response = Response.stream(body(), headers={"x-demo": "1"}) + assert response.status == 200 + assert response.content_type == "text/plain; charset=utf-8" + response.set_cookie("foo", "bar") + assert await _collect(response) == [ + { + "type": "http.response.start", + "status": 200, + "headers": [ + [b"x-demo", b"1"], + [b"content-type", b"text/plain; charset=utf-8"], + [b"set-cookie", b"foo=bar; Path=/; SameSite=lax"], + ], + }, + {"type": "http.response.body", "body": b"one\n", "more_body": True}, + {"type": "http.response.body", "body": b"two\n", "more_body": True}, + { + "type": "http.response.body", + "body": "café\n".encode(), + "more_body": True, + }, + {"type": "http.response.body", "body": b""}, + ] + + +@pytest.mark.asyncio +async def test_response_stream_status_and_content_type(): + async def body(): + yield "{}" + + response = Response.stream(body(), status=201, content_type="application/x-ndjson") + events = await _collect(response) + assert events[0]["status"] == 201 + assert [b"content-type", b"application/x-ndjson"] in events[0]["headers"] + + +@pytest.mark.asyncio +async def test_response_stream_any_async_iterator(): + class Countdown: + def __init__(self): + self.n = 3 + + def __aiter__(self): + return self + + async def __anext__(self): + if not self.n: + raise StopAsyncIteration + self.n -= 1 + return str(self.n) + + events = await _collect(Response.stream(Countdown())) + assert [event["body"] for event in events[1:]] == [b"2", b"1", b"0", b""] + + +@pytest.mark.parametrize("body", ("a string", b"bytes", ["a", "list"], None)) +def test_response_stream_requires_async_iterator(body): + with pytest.raises(TypeError, match="async iterator"): + Response.stream(body) + + +@pytest.mark.asyncio +async def test_response_stream_error_ends_without_final_chunk(): + cleaned_up = [] + + async def body(): + try: + yield "one" + raise ValueError("went wrong") + finally: + cleaned_up.append(True) + + events = [] + + async def send(event): + events.append(event) + + with pytest.raises(ValueError, match="went wrong"): + await Response.stream(body()).asgi_send(send) + # No terminating chunk, so the client can tell the response is incomplete + assert events[-1] == { + "type": "http.response.body", + "body": b"one", + "more_body": True, + } + assert cleaned_up == [True] + + +@pytest.mark.asyncio +async def test_response_stream_closes_generator_on_disconnect(): + cleaned_up = [] + + async def body(): + try: + yield "one" + yield "two" + yield "three" + finally: + cleaned_up.append(True) + + sent = [] + + async def send(event): + if event.get("body") == b"two": + raise OSError("client disconnected") + sent.append(event) + + with pytest.raises(OSError): + await Response.stream(body()).asgi_send(send) + assert cleaned_up == [True] + assert [event.get("body") for event in sent[1:]] == [b"one"] + + +class _StreamRoutesPlugin: + __name__ = "StreamRoutesPlugin" + + @hookimpl + def register_routes(self): + async def stream(request): + async def body(): + for i in range(int(request.args.get("n", 3))): + yield f"line {i}\n" + + return Response.stream(body(), headers={"x-streamed": "yes"}) + + async def broken(request): + async def body(): + yield "partial" + raise ValueError("stream failed") + + return Response.stream(body()) + + async def broken_before_first_chunk(request): + raise ValueError("failed before the response started") + + return [ + (r"^/-/stream-demo$", stream), + (r"^/-/stream-broken$", broken), + (r"^/-/stream-broken-early$", broken_before_first_chunk), + ] + + +@pytest.fixture +def stream_routes(): + pm.register(_StreamRoutesPlugin(), name="stream_routes") + try: + yield + finally: + pm.unregister(name="stream_routes") + + +@pytest.mark.asyncio +async def test_response_stream_from_view(stream_routes): + ds = Datasette(memory=True) + try: + response = await ds.client.get("/-/stream-demo?n=4") + assert response.status_code == 200 + assert response.headers["x-streamed"] == "yes" + assert response.headers["content-type"] == "text/plain; charset=utf-8" + assert response.text == "line 0\nline 1\nline 2\nline 3\n" + # A stream that yields nothing is an empty 200 response + response = await ds.client.get("/-/stream-demo?n=0") + assert response.status_code == 200 + assert response.text == "" + finally: + ds.close() + + +@pytest.mark.asyncio +async def test_response_stream_error_in_view_is_not_an_error_page(stream_routes): + ds = Datasette(memory=True) + try: + # Failing part way through cannot become a 500 page, because the + # 200 status has already been sent - the exception reaches the server + with pytest.raises(ValueError, match="stream failed"): + await ds.client.get("/-/stream-broken") + # An error before the response starts is still a regular 500 + response = await ds.client.get("/-/stream-broken-early") + assert response.status_code == 500 + finally: + ds.close() From 6516cd2d30034a50d94cc6c2ce4058b6489bda58 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:19:06 +0000 Subject: [PATCH 02/10] Output renderers can declare extras, passed to render as extras= register_output_renderer() dictionaries can now include an "extras" key listing the ?_extra= extras the format needs. Datasette resolves them, only for that format, and passes them to the render function as a new extras argument - a dictionary which also includes any extras requested in the URL. Extras that are not available for the current page (count on an arbitrary SQL query, for example) are omitted from the dictionary. Refs #2770, #2186, #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 10 ++ datasette/views/base.py | 12 +++ datasette/views/database.py | 12 ++- datasette/views/row.py | 10 +- datasette/views/table.py | 8 ++ docs/changelog.rst | 1 + docs/plugin_hooks.rst | 31 ++++++- tests/test_renderer_extras.py | 166 ++++++++++++++++++++++++++++++++++ 8 files changed, 247 insertions(+), 3 deletions(-) create mode 100644 tests/test_renderer_extras.py diff --git a/datasette/app.py b/datasette/app.py index 17db4439c7..9d8fc6bb66 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -590,6 +590,7 @@ def __init__( self.renderers = {} # File extension -> (renderer, can_render) functions # File extension -> label, description, is_binary and is_webpage self._renderer_options = {} + self._renderer_extras = {} # File extension -> extras the renderer declared self.version_note = version_note if self.setting("num_sql_threads") == 0: self.executor = None @@ -2572,6 +2573,15 @@ def _register_renderers(self): renderer.get("render") or renderer["callback"], renderer.get("can_render") or (lambda: True), ) + # Extras to resolve and pass to the render function as extras= + declared_extras = renderer.get("extras") or [] + if isinstance(declared_extras, str) or not all( + isinstance(name, str) for name in declared_extras + ): + raise StartupError( + f"Output renderer '{extension}' extras must be a list of strings" + ) + self._renderer_extras[extension] = list(declared_extras) # How the export dialog presents this format is_binary = bool(renderer.get("is_binary")) is_webpage = bool(renderer.get("is_webpage")) diff --git a/datasette/views/base.py b/datasette/views/base.py index f0dd26c9d9..fe3136ff59 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -2,6 +2,7 @@ import hashlib import sys +from datasette.extras import extra_names_from_request from datasette.utils import ( EscapeHtmlWriter, InvalidSql, @@ -175,6 +176,17 @@ async def view(request, send): return view +def extras_for_renderer(datasette, request, format_, data): + """ + The extras= dictionary passed to an output renderer's render function: + the extras it declared when it was registered, plus any requested using + ?_extra=. Extras that are not available for this type of page are omitted. + """ + names = set(datasette._renderer_extras.get(format_) or []) + names.update(extra_names_from_request(request)) + return {name: data[name] for name in sorted(names) if name in data} + + # Formats that stream_csv() writes, with their content type for downloads. # TSV uses Excel's tab-separated dialect, so it pastes cleanly into Excel and # Google Sheets: values containing tabs, newlines or double quotes are wrapped diff --git a/datasette/views/database.py b/datasette/views/database.py index 7fc12c34c0..c45764444f 100644 --- a/datasette/views/database.py +++ b/datasette/views/database.py @@ -47,7 +47,14 @@ from datasette.write_sql import QueryWriteRejected from . import Context -from .base import DatasetteError, View, is_csv_format, stream_csv, tsv_export_path +from .base import ( + DatasetteError, + View, + extras_for_renderer, + is_csv_format, + stream_csv, + tsv_export_path, +) from .query_helpers import ( _block_framing, _ensure_stored_query_execution_permissions, @@ -912,6 +919,8 @@ async def fetch_data_for_csv(request, _next=None): data = {"ok": True, "rows": rows, "columns": columns} extras = extra_names_from_request(request) table_extra_registry.validate_requested(extras, ExtraScope.QUERY) + # Plus any extras declared by the output renderer for this format + extras.update(datasette._renderer_extras.get(format_) or []) if extras: query_extra_context = QueryExtraContext( datasette=datasette, @@ -944,6 +953,7 @@ async def fetch_data_for_csv(request, _next=None): view_name="table", truncated=results.truncated if results else False, error=query_error, + extras=extras_for_renderer(datasette, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, diff --git a/datasette/views/row.py b/datasette/views/row.py index 752411b5ef..6e279ca530 100644 --- a/datasette/views/row.py +++ b/datasette/views/row.py @@ -38,6 +38,7 @@ from .base import ( BaseView, DatasetteError, + extras_for_renderer, is_csv_format, stream_csv, tsv_export_path, @@ -191,6 +192,9 @@ async def get(self, request): if format_ == "html": # HTML views default to expanding all foreign key labels data_kwargs["default_labels"] = True + elif self.ds._renderer_extras.get(format_): + # Extras declared by the output renderer for this format + data_kwargs["renderer_extras"] = self.ds._renderer_extras[format_] extra_template_data = {} start = time.perf_counter() @@ -254,6 +258,7 @@ async def get(self, request): view_name=self.name, truncated=False, # TODO: support this error=data.get("error"), + extras=extras_for_renderer(self.ds, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, @@ -423,7 +428,7 @@ def set_response_headers(self, response, ttl, request=None): add_cors_headers(response.headers) return response - async def data(self, request, default_labels=False): + async def data(self, request, default_labels=False, renderer_extras=None): db, table, resource = await _database_and_table_resource_from_request( self.ds, request ) @@ -642,6 +647,9 @@ async def template_data(): if request.url_vars.get("format"): # Data formats reject unknown extras; HTML ignores them table_extra_registry.validate_requested(extras, ExtraScope.ROW) + if renderer_extras: + # Any that are not available for rows are skipped when resolved + extras.update(renderer_extras) # Process extras row_extra_context = RowExtraContext( diff --git a/datasette/views/table.py b/datasette/views/table.py index 339d23b727..20fb76cd88 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -67,6 +67,7 @@ from .base import ( BaseView, DatasetteError, + extras_for_renderer, is_csv_format, stream_csv, tsv_export_path, @@ -1987,6 +1988,7 @@ async def table_view_traced(datasette, request): extra_extras=extra_extras, context_for_html_hack=context_for_html_hack, default_labels=default_labels, + renderer_extras=datasette._renderer_extras.get(format_), ) if isinstance(view_data, Response): return view_data @@ -2038,6 +2040,7 @@ async def fetch_data(request, _next=None): view_name="table", truncated=False, error=None, + extras=extras_for_renderer(datasette, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, @@ -2375,6 +2378,7 @@ async def table_view_data( context_for_html_hack=False, default_labels=False, _next=None, + renderer_extras=None, ): extra_extras = extra_extras or set() # We have a table or view @@ -2617,6 +2621,10 @@ async def table_view_data( # Data formats reject unknown extras; the HTML path (which passes # extra_extras={"_html"}) resolves internal extras of its own table_extra_registry.validate_requested(extras, ExtraScope.TABLE) + if renderer_extras: + # Extras declared by the output renderer for this format. Any that + # are not available for tables are skipped when extras are resolved. + extras.update(renderer_extras) if any(k for k in request.args if k == "_facet" or k.startswith("_facet_")): extras.add("facet_results") if request.args.get("_shape") == "object": diff --git a/docs/changelog.rst b/docs/changelog.rst index fc31a1b45c..a52e4fa5f1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,7 @@ Unreleased ---------- - 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`. +- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function as a new ``extras`` argument. (:issue:`2770`, :issue:`2186`) - The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests. - Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ```` element for that name matched a class used by Datasette's own CSS and JavaScript. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 7d23ce1d99..3ccd57f6d9 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -597,7 +597,7 @@ This will register ``render_demo`` to be called when paths with the extension `` ``render_demo`` is a Python function. It can be a regular function or an ``async def render_demo()`` awaitable function, depending on if it needs to make any asynchronous calls. -``can_render_demo`` is a Python function (or ``async def`` function) which accepts the same arguments as ``render_demo`` but just returns ``True`` or ``False``. It lets Datasette know if the current SQL query can be represented by the plugin - and hence influence if a link to this output format is displayed in the user interface. If you omit the ``"can_render"`` key from the dictionary every query will be treated as being supported by the plugin. +``can_render_demo`` is a Python function (or ``async def`` function) which accepts the same arguments as ``render_demo``, apart from ``extras``, but just returns ``True`` or ``False``. It lets Datasette know if the current SQL query can be represented by the plugin - and hence influence if a link to this output format is displayed in the user interface. If you omit the ``"can_render"`` key from the dictionary every query will be treated as being supported by the plugin. The dictionary can also include these optional keys, which control how the format is shown in the :ref:`Export data dialog `: @@ -627,6 +627,32 @@ Formats that set neither option are offered with all four actions: **Copy**, **V "is_binary": True, } +The dictionary can also include an optional ``"extras"`` key, listing the :ref:`extras ` the format needs. These are the same names that can be passed to ``?_extra=`` in the JSON API. Datasette calculates them and passes them to the ``"render"`` function as the ``extras`` argument described below: + +.. code-block:: python + + def render_summary(rows, extras): + return Response.text( + "Showing {} of {} rows {}".format( + len(rows), + extras.get("count"), + extras.get("human_description_en") or "", + ) + ) + + + @hookimpl + def register_output_renderer(datasette): + return { + "extension": "summary", + "render": render_summary, + "extras": ["count", "human_description_en"], + } + +Extras are only calculated for the format that declared them, so a format that lists ``"count"`` does not make any other format slower. + +Not every extra is available on every page: ``count`` and ``human_description_en`` exist for tables but not for arbitrary SQL queries, for example. An extra that is not available for the current page is left out of the ``extras`` dictionary, so use ``extras.get(name)`` unless you know the extra is available everywhere your format is used. + When a request is received, the ``"render"`` callback function is called with zero or more of the following arguments. Datasette will inspect your callback function and pass arguments that match its function signature. ``datasette`` - :ref:`internals_datasette` @@ -662,6 +688,9 @@ When a request is received, the ``"render"`` callback function is called with ze ``view_name`` - string The name of the current view being called. ``index``, ``database``, ``table``, and ``row`` are the most important ones. +``extras`` - dictionary + The :ref:`extras ` this format declared using its ``"extras"`` key, plus any that were requested using ``?_extra=`` in the URL. Keys are the names of the extras. Extras that are not available for the current page are omitted. + The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller. It can also return a dictionary with the following keys. This format is **deprecated** as-of Datasette 0.49 and will be removed by Datasette 1.0. diff --git a/tests/test_renderer_extras.py b/tests/test_renderer_extras.py new file mode 100644 index 0000000000..e0c015a96d --- /dev/null +++ b/tests/test_renderer_extras.py @@ -0,0 +1,166 @@ +""" +Output renderers can declare the extras they need using "extras" in their +register_output_renderer() dictionary, then receive them as extras= +""" + +import pytest +import pytest_asyncio + +from datasette import hookimpl +from datasette.app import Datasette +from datasette.plugins import pm +from datasette.utils import StartupError +from datasette.utils.asgi import Response + + +class _ExtrasRendererPlugin: + __name__ = "ExtrasRendererPlugin" + + @hookimpl + def register_output_renderer(self): + def render_declared(extras, rows): + return Response.json({"extras": extras, "num_rows": len(rows)}) + + def render_none_declared(extras): + return Response.json({"extras": extras}) + + def render_without_extras_argument(): + return Response.text("ok") + + return [ + { + "extension": "declared", + "render": render_declared, + "extras": ["count", "human_description_en", "primary_keys"], + }, + {"extension": "nonedeclared", "render": render_none_declared}, + { + "extension": "noargument", + "render": render_without_extras_argument, + "extras": ["count"], + }, + ] + + +@pytest.fixture +def ds(): + pm.register(_ExtrasRendererPlugin(), name="extras_renderer") + ds = Datasette(memory=True) + try: + yield ds + finally: + ds.close() + pm.unregister(name="extras_renderer") + + +@pytest_asyncio.fixture +async def db(ds): + db = ds.add_memory_database("renderer_extras_test", name="data") + await db.execute_write_script(""" + drop table if exists dogs; + create table dogs (id integer primary key, name text, age integer); + insert into dogs (name, age) values ('Cleo', 5), ('Pancakes', 4), ('Fido', 3); + """) + return db + + +@pytest.mark.asyncio +async def test_table_renderer_receives_declared_extras(ds, db): + response = await ds.client.get("/data/dogs.declared?age__gt=3&_size=1") + assert response.status_code == 200 + assert response.json() == { + "extras": { + # The count is of every matching row, not just this page + "count": 2, + "human_description_en": "where age > 3", + "primary_keys": ["id"], + }, + "num_rows": 1, + } + + +@pytest.mark.asyncio +async def test_query_renderer_omits_extras_not_available_for_queries(ds, db): + # count, human_description_en and primary_keys are all table extras + response = await ds.client.get("/data/-/query.declared?sql=select+*+from+dogs") + assert response.status_code == 200 + assert response.json() == {"extras": {}, "num_rows": 3} + + +@pytest.mark.asyncio +async def test_row_renderer_omits_extras_not_available_for_rows(ds, db): + response = await ds.client.get("/data/dogs/1.declared") + assert response.status_code == 200 + # primary_keys is available for rows, the other two are not + assert response.json() == {"extras": {"primary_keys": ["id"]}, "num_rows": 1} + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,expected", + ( + ("/data/dogs.nonedeclared", {}), + ("/data/dogs.nonedeclared?_extra=count", {"count": 3}), + ( + "/data/-/query.nonedeclared?sql=select+1+as+one&_extra=columns", + {"columns": ["one"]}, + ), + ("/data/dogs/1.nonedeclared?_extra=primary_keys", {"primary_keys": ["id"]}), + # Requested extras are added to the declared ones + ( + "/data/dogs.declared?_extra=is_view", + { + "count": 3, + "human_description_en": "", + "primary_keys": ["id"], + "is_view": False, + }, + ), + ), +) +async def test_renderer_receives_extras_requested_in_url(ds, db, path, expected): + response = await ds.client.get(path) + assert response.status_code == 200 + assert response.json()["extras"] == expected + + +@pytest.mark.asyncio +async def test_unknown_requested_extra_is_still_an_error(ds, db): + response = await ds.client.get("/data/dogs.declared?_extra=nope") + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_render_function_does_not_have_to_accept_extras(ds, db): + response = await ds.client.get("/data/dogs.noargument") + assert response.status_code == 200 + assert response.text == "ok" + + +@pytest.mark.asyncio +async def test_declared_extras_do_not_leak_into_json(ds, db): + # Declaring an extra for one format must not add it to any other format + data = (await ds.client.get("/data/dogs.json")).json() + assert "count" not in data + assert "human_description_en" not in data + + +@pytest.mark.parametrize("extras", ("count", [1, 2], [None])) +def test_extras_must_be_a_list_of_strings(extras): + class BadPlugin: + __name__ = "BadPlugin" + + @hookimpl + def register_output_renderer(self): + return { + "extension": "bad", + "render": lambda: Response.text("x"), + "extras": extras, + } + + pm.register(BadPlugin(), name="bad_extras_renderer") + try: + with pytest.raises(StartupError, match="extras must be a list of strings"): + Datasette(memory=True) + finally: + pm.unregister(name="bad_extras_renderer") From 7e2db2643e5673df36496dc1dc21aab15418f481 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:41:38 +0000 Subject: [PATCH 03/10] JSON renderer no longer uses data= or args= The built-in JSON renderer now builds its output from rows, columns and extras, the same documented arguments available to plugin renderers. To make that possible the extras= dictionary now holds everything a page's JSON returns alongside its rows: declared and requested extras plus the keys that type of page always includes, such as next and next_url for tables. Applying transform_value() from column types moves into the JSON renderer for non-HTML table requests. Refs #2770, #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/renderer.py | 54 ++++++++++++++++++++++++++--------- datasette/views/base.py | 19 +++++++++--- datasette/views/table.py | 22 ++++++-------- docs/changelog.rst | 2 +- docs/plugin_hooks.rst | 2 +- tests/test_renderer_extras.py | 44 ++++++++++++++++++++++++---- 6 files changed, 106 insertions(+), 37 deletions(-) diff --git a/datasette/renderer.py b/datasette/renderer.py index e0530e9034..96dca10f46 100644 --- a/datasette/renderer.py +++ b/datasette/renderer.py @@ -1,6 +1,5 @@ import json -from datasette.extras import extra_names_from_request from datasette.utils import ( CustomJSONEncoder, error_body, @@ -43,10 +42,47 @@ def convert_specific_columns_to_json(rows, columns, json_cols): return new_rows -def json_renderer(request, args, data, error, truncated=None): +async def apply_column_type_transforms(datasette, database, table, rows): + """ + Return rows as dictionaries, with transform_value() applied for any + columns that have been assigned a column type. + """ + ct_map = await datasette.get_column_types(database, table) + transformed_rows = [] + for row in rows: + row_dict = dict(row) + for col_name, ct in ct_map.items(): + if col_name in row_dict: + row_dict[col_name] = await ct.transform_value( + row_dict[col_name], datasette + ) + transformed_rows.append(row_dict) + return transformed_rows + + +async def json_renderer( + datasette, + request, + rows, + columns, + extras, + error, + database, + table, + view_name, + truncated=None, +): """Render a response as JSON""" + args = request.args status_code = 200 + if view_name == "table" and table and not error: + # Table pages apply transform_value() from any column types + rows = await apply_column_type_transforms(datasette, database, table, rows) + + # Everything other than the rows comes from the extras + data = {"ok": True, **extras, "rows": rows} + # Handle the _json= parameter which may modify data["rows"] json_cols = [] if "_json" in args: @@ -60,24 +96,22 @@ def json_renderer(request, args, data, error, truncated=None): and any(pk in json_cols for pk in pks) ): object_keys = [] - columns = data.get("columns") for row in data["rows"]: if columns and not isinstance(row, dict): row = dict(zip(columns, row)) object_keys.append(path_from_row_pks(row, pks, False)) - if json_cols and "rows" in data: + if json_cols: data["rows"] = convert_specific_columns_to_json( - data["rows"], data.get("columns"), json_cols + data["rows"], columns, json_cols ) # unless _json_infinity=1 requested, replace infinity with None - if "rows" in data and not value_as_boolean(args.get("_json_infinity", "0")): + if not value_as_boolean(args.get("_json_infinity", "0")): data["rows"] = [remove_infinites(row) for row in data["rows"]] # Deal with the _shape option shape = args.get("_shape", "objects") # if there's an error, ignore the shape entirely - data["ok"] = True if error: shape = "objects" status_code = 400 @@ -93,7 +127,6 @@ def json_renderer(request, args, data, error, truncated=None): else: data = [row[0] for row in data["rows"]] elif shape in ("objects", "object", "array"): - columns = data.get("columns") rows = data.get("rows") if rows and columns and not isinstance(rows[0], dict): data["rows"] = [dict(zip(columns, row)) for row in rows] @@ -134,11 +167,6 @@ def json_renderer(request, args, data, error, truncated=None): status_code = 400 data = error_body(f"Invalid _shape: {shape}", status_code) - # Don't include "columns" in output - # https://github.com/simonw/datasette/issues/2136 - if isinstance(data, dict) and "columns" not in extra_names_from_request(request): - data.pop("columns", None) - # Handle _nl option for _shape=array nl = args.get("_nl", "") if nl and shape == "array": diff --git a/datasette/views/base.py b/datasette/views/base.py index fe3136ff59..78caa71e23 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -178,13 +178,24 @@ async def view(request, send): def extras_for_renderer(datasette, request, format_, data): """ - The extras= dictionary passed to an output renderer's render function: - the extras it declared when it was registered, plus any requested using - ?_extra=. Extras that are not available for this type of page are omitted. + The extras= dictionary passed to an output renderer's render function. + + This is everything the JSON for this page returns alongside its rows: + the keys that type of page always includes (such as next and next_url + for tables), the extras the renderer declared when it was registered + and any requested using ?_extra=. Extras that are not available for + this type of page are omitted. """ names = set(datasette._renderer_extras.get(format_) or []) names.update(extra_names_from_request(request)) - return {name: data[name] for name in sorted(names) if name in data} + return { + key: value + for key, value in data.items() + if key not in ("ok", "rows") + # Row and query pages always have columns, but it is only an + # extra if it was asked for - see issue 2136 + and (key != "columns" or "columns" in names) + } # Formats that stream_csv() writes, with their content type for downloads. diff --git a/datasette/views/table.py b/datasette/views/table.py index 20fb76cd88..0159e8216f 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -22,6 +22,7 @@ from datasette.extras import ExtraScope, extra_names_from_request from datasette.filters import Filters from datasette.plugins import pm +from datasette.renderer import apply_column_type_transforms from datasette.resources import DatabaseResource, TableResource from datasette.utils import ( CustomJSONEncoder, @@ -2695,19 +2696,14 @@ async def table_view_data( include_internal=bool(extra_extras), ) ) - raw_sqlite_rows = rows[:page_size] - # Apply transform_value for columns with assigned types - ct_map = await datasette.get_column_types(database_name, table_name) - transformed_rows = [] - for r in raw_sqlite_rows: - row_dict = dict(r) - for col_name, ct in ct_map.items(): - if col_name in row_dict: - row_dict[col_name] = await ct.transform_value( - row_dict[col_name], datasette - ) - transformed_rows.append(row_dict) - data["rows"] = transformed_rows + if context_for_html_hack: + # Apply transform_value for columns with assigned types + data["rows"] = await apply_column_type_transforms( + datasette, database_name, table_name, rows[:page_size] + ) + else: + # The JSON renderer applies those transforms itself + data["rows"] = [dict(row) for row in rows[:page_size]] if context_for_html_hack: data["count_truncated"] = count_is_truncated( diff --git a/docs/changelog.rst b/docs/changelog.rst index a52e4fa5f1..85145055ff 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,7 +10,7 @@ Unreleased ---------- - 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`. -- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function as a new ``extras`` argument. (:issue:`2770`, :issue:`2186`) +- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function as a new ``extras`` argument, which also includes ``next`` and ``next_url`` on table pages. (:issue:`2770`, :issue:`2186`) - The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests. - Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ```` element for that name matched a class used by Datasette's own CSS and JavaScript. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 3ccd57f6d9..8dc307c1c1 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -689,7 +689,7 @@ When a request is received, the ``"render"`` callback function is called with ze The name of the current view being called. ``index``, ``database``, ``table``, and ``row`` are the most important ones. ``extras`` - dictionary - The :ref:`extras ` this format declared using its ``"extras"`` key, plus any that were requested using ``?_extra=`` in the URL. Keys are the names of the extras. Extras that are not available for the current page are omitted. + Everything the JSON version of this page returns alongside its rows: the :ref:`extras ` this format declared using its ``"extras"`` key, any that were requested using ``?_extra=`` in the URL, and the keys that type of page always includes. For table pages those are ``next``, the token for the next page of results, and ``next_url``, the URL of that page in this format - both are ``None`` on the last page. Extras that are not available for the current page are omitted. The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller. diff --git a/tests/test_renderer_extras.py b/tests/test_renderer_extras.py index e0c015a96d..13c997f214 100644 --- a/tests/test_renderer_extras.py +++ b/tests/test_renderer_extras.py @@ -70,8 +70,12 @@ async def test_table_renderer_receives_declared_extras(ds, db): assert response.status_code == 200 assert response.json() == { "extras": { + # Tables always include these two + "next": "1", + "next_url": "http://localhost/data/dogs.declared?age__gt=3&_size=1&_next=1", # The count is of every matching row, not just this page "count": 2, + "count_truncated": False, "human_description_en": "where age > 3", "primary_keys": ["id"], }, @@ -91,26 +95,45 @@ async def test_query_renderer_omits_extras_not_available_for_queries(ds, db): async def test_row_renderer_omits_extras_not_available_for_rows(ds, db): response = await ds.client.get("/data/dogs/1.declared") assert response.status_code == 200 - # primary_keys is available for rows, the other two are not - assert response.json() == {"extras": {"primary_keys": ["id"]}, "num_rows": 1} + data = response.json() + assert data["num_rows"] == 1 + extras = data["extras"] + # count and human_description_en are not available for rows + assert "count" not in extras + assert "human_description_en" not in extras + # Rows always include these + assert isinstance(extras.pop("query_ms"), float) + assert extras == { + "database": "data", + "table": "dogs", + "primary_keys": ["id"], + "primary_key_values": ["1"], + } @pytest.mark.asyncio @pytest.mark.parametrize( "path,expected", ( - ("/data/dogs.nonedeclared", {}), - ("/data/dogs.nonedeclared?_extra=count", {"count": 3}), + ("/data/dogs.nonedeclared", {"next": None, "next_url": None}), + ( + "/data/dogs.nonedeclared?_extra=count", + {"next": None, "next_url": None, "count": 3, "count_truncated": False}, + ), + # columns is only included if it was asked for + ("/data/-/query.nonedeclared?sql=select+1+as+one", {}), ( "/data/-/query.nonedeclared?sql=select+1+as+one&_extra=columns", {"columns": ["one"]}, ), - ("/data/dogs/1.nonedeclared?_extra=primary_keys", {"primary_keys": ["id"]}), # Requested extras are added to the declared ones ( "/data/dogs.declared?_extra=is_view", { + "next": None, + "next_url": None, "count": 3, + "count_truncated": False, "human_description_en": "", "primary_keys": ["id"], "is_view": False, @@ -164,3 +187,14 @@ def register_output_renderer(self): Datasette(memory=True) finally: pm.unregister(name="bad_extras_renderer") + + +def test_json_renderer_uses_documented_arguments_only(ds): + # The built-in JSON renderer is called like any plugin renderer, so it + # must not depend on the undocumented data= and args= arguments + import inspect + + render, _ = ds.renderers["json"] + parameters = set(inspect.signature(render).parameters) + assert not parameters & {"data", "args"} + assert {"rows", "columns", "extras"} <= parameters From 7702881008b1f4cfe06c06f4361a444318ed0e31 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:49:08 +0000 Subject: [PATCH 04/10] Rename the extras render argument to page The dictionary passed to output renderers holds everything a page's JSON returns alongside its rows - not only extras - so extras was a misleading name for it. The "extras" registration key is unchanged. Refs #2770, #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/renderer.py | 6 +++--- datasette/views/base.py | 4 ++-- datasette/views/database.py | 4 ++-- datasette/views/row.py | 4 ++-- datasette/views/table.py | 4 ++-- docs/changelog.rst | 2 +- docs/plugin_hooks.rst | 14 +++++++------- tests/test_renderer_extras.py | 34 +++++++++++++++++----------------- 8 files changed, 36 insertions(+), 36 deletions(-) diff --git a/datasette/renderer.py b/datasette/renderer.py index 96dca10f46..30fa3bae0e 100644 --- a/datasette/renderer.py +++ b/datasette/renderer.py @@ -65,7 +65,7 @@ async def json_renderer( request, rows, columns, - extras, + page, error, database, table, @@ -80,8 +80,8 @@ async def json_renderer( # Table pages apply transform_value() from any column types rows = await apply_column_type_transforms(datasette, database, table, rows) - # Everything other than the rows comes from the extras - data = {"ok": True, **extras, "rows": rows} + # Everything other than the rows comes from the page dictionary + data = {"ok": True, **page, "rows": rows} # Handle the _json= parameter which may modify data["rows"] json_cols = [] diff --git a/datasette/views/base.py b/datasette/views/base.py index 78caa71e23..74b83f6637 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -176,9 +176,9 @@ async def view(request, send): return view -def extras_for_renderer(datasette, request, format_, data): +def page_for_renderer(datasette, request, format_, data): """ - The extras= dictionary passed to an output renderer's render function. + The page= dictionary passed to an output renderer's render function. This is everything the JSON for this page returns alongside its rows: the keys that type of page always includes (such as next and next_url diff --git a/datasette/views/database.py b/datasette/views/database.py index c45764444f..f54b86cce5 100644 --- a/datasette/views/database.py +++ b/datasette/views/database.py @@ -50,8 +50,8 @@ from .base import ( DatasetteError, View, - extras_for_renderer, is_csv_format, + page_for_renderer, stream_csv, tsv_export_path, ) @@ -953,7 +953,7 @@ async def fetch_data_for_csv(request, _next=None): view_name="table", truncated=results.truncated if results else False, error=query_error, - extras=extras_for_renderer(datasette, request, format_, data), + page=page_for_renderer(datasette, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, diff --git a/datasette/views/row.py b/datasette/views/row.py index 6e279ca530..32e2c944c7 100644 --- a/datasette/views/row.py +++ b/datasette/views/row.py @@ -38,8 +38,8 @@ from .base import ( BaseView, DatasetteError, - extras_for_renderer, is_csv_format, + page_for_renderer, stream_csv, tsv_export_path, ) @@ -258,7 +258,7 @@ async def get(self, request): view_name=self.name, truncated=False, # TODO: support this error=data.get("error"), - extras=extras_for_renderer(self.ds, request, format_, data), + page=page_for_renderer(self.ds, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, diff --git a/datasette/views/table.py b/datasette/views/table.py index 0159e8216f..9fb00f2f04 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -68,8 +68,8 @@ from .base import ( BaseView, DatasetteError, - extras_for_renderer, is_csv_format, + page_for_renderer, stream_csv, tsv_export_path, ) @@ -2041,7 +2041,7 @@ async def fetch_data(request, _next=None): view_name="table", truncated=False, error=None, - extras=extras_for_renderer(datasette, request, format_, data), + page=page_for_renderer(datasette, request, format_, data), # These will be deprecated in Datasette 1.0: args=request.args, data=data, diff --git a/docs/changelog.rst b/docs/changelog.rst index 85145055ff..ce461d95fd 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,7 +10,7 @@ Unreleased ---------- - 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`. -- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function as a new ``extras`` argument, which also includes ``next`` and ``next_url`` on table pages. (:issue:`2770`, :issue:`2186`) +- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function in a new ``page`` argument, a dictionary which also includes ``next`` and ``next_url`` on table pages. (:issue:`2770`, :issue:`2186`) - The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests. - Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ```` element for that name matched a class used by Datasette's own CSS and JavaScript. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 8dc307c1c1..9d35640579 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -597,7 +597,7 @@ This will register ``render_demo`` to be called when paths with the extension `` ``render_demo`` is a Python function. It can be a regular function or an ``async def render_demo()`` awaitable function, depending on if it needs to make any asynchronous calls. -``can_render_demo`` is a Python function (or ``async def`` function) which accepts the same arguments as ``render_demo``, apart from ``extras``, but just returns ``True`` or ``False``. It lets Datasette know if the current SQL query can be represented by the plugin - and hence influence if a link to this output format is displayed in the user interface. If you omit the ``"can_render"`` key from the dictionary every query will be treated as being supported by the plugin. +``can_render_demo`` is a Python function (or ``async def`` function) which accepts the same arguments as ``render_demo``, apart from ``page``, but just returns ``True`` or ``False``. It lets Datasette know if the current SQL query can be represented by the plugin - and hence influence if a link to this output format is displayed in the user interface. If you omit the ``"can_render"`` key from the dictionary every query will be treated as being supported by the plugin. The dictionary can also include these optional keys, which control how the format is shown in the :ref:`Export data dialog `: @@ -627,16 +627,16 @@ Formats that set neither option are offered with all four actions: **Copy**, **V "is_binary": True, } -The dictionary can also include an optional ``"extras"`` key, listing the :ref:`extras ` the format needs. These are the same names that can be passed to ``?_extra=`` in the JSON API. Datasette calculates them and passes them to the ``"render"`` function as the ``extras`` argument described below: +The dictionary can also include an optional ``"extras"`` key, listing the :ref:`extras ` the format needs. These are the same names that can be passed to ``?_extra=`` in the JSON API. Datasette calculates them and passes them to the ``"render"`` function in the ``page`` argument described below: .. code-block:: python - def render_summary(rows, extras): + def render_summary(rows, page): return Response.text( "Showing {} of {} rows {}".format( len(rows), - extras.get("count"), - extras.get("human_description_en") or "", + page.get("count"), + page.get("human_description_en") or "", ) ) @@ -651,7 +651,7 @@ The dictionary can also include an optional ``"extras"`` key, listing the :ref:` Extras are only calculated for the format that declared them, so a format that lists ``"count"`` does not make any other format slower. -Not every extra is available on every page: ``count`` and ``human_description_en`` exist for tables but not for arbitrary SQL queries, for example. An extra that is not available for the current page is left out of the ``extras`` dictionary, so use ``extras.get(name)`` unless you know the extra is available everywhere your format is used. +Not every extra is available on every page: ``count`` and ``human_description_en`` exist for tables but not for arbitrary SQL queries, for example. An extra that is not available for the current page is left out of the ``page`` dictionary, so use ``page.get(name)`` unless you know the extra is available everywhere your format is used. When a request is received, the ``"render"`` callback function is called with zero or more of the following arguments. Datasette will inspect your callback function and pass arguments that match its function signature. @@ -688,7 +688,7 @@ When a request is received, the ``"render"`` callback function is called with ze ``view_name`` - string The name of the current view being called. ``index``, ``database``, ``table``, and ``row`` are the most important ones. -``extras`` - dictionary +``page`` - dictionary Everything the JSON version of this page returns alongside its rows: the :ref:`extras ` this format declared using its ``"extras"`` key, any that were requested using ``?_extra=`` in the URL, and the keys that type of page always includes. For table pages those are ``next``, the token for the next page of results, and ``next_url``, the URL of that page in this format - both are ``None`` on the last page. Extras that are not available for the current page are omitted. The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller. diff --git a/tests/test_renderer_extras.py b/tests/test_renderer_extras.py index 13c997f214..31bf392dc4 100644 --- a/tests/test_renderer_extras.py +++ b/tests/test_renderer_extras.py @@ -1,6 +1,6 @@ """ Output renderers can declare the extras they need using "extras" in their -register_output_renderer() dictionary, then receive them as extras= +register_output_renderer() dictionary, then receive them in page= """ import pytest @@ -18,13 +18,13 @@ class _ExtrasRendererPlugin: @hookimpl def register_output_renderer(self): - def render_declared(extras, rows): - return Response.json({"extras": extras, "num_rows": len(rows)}) + def render_declared(page, rows): + return Response.json({"page": page, "num_rows": len(rows)}) - def render_none_declared(extras): - return Response.json({"extras": extras}) + def render_none_declared(page): + return Response.json({"page": page}) - def render_without_extras_argument(): + def render_without_page_argument(): return Response.text("ok") return [ @@ -36,7 +36,7 @@ def render_without_extras_argument(): {"extension": "nonedeclared", "render": render_none_declared}, { "extension": "noargument", - "render": render_without_extras_argument, + "render": render_without_page_argument, "extras": ["count"], }, ] @@ -69,7 +69,7 @@ async def test_table_renderer_receives_declared_extras(ds, db): response = await ds.client.get("/data/dogs.declared?age__gt=3&_size=1") assert response.status_code == 200 assert response.json() == { - "extras": { + "page": { # Tables always include these two "next": "1", "next_url": "http://localhost/data/dogs.declared?age__gt=3&_size=1&_next=1", @@ -88,7 +88,7 @@ async def test_query_renderer_omits_extras_not_available_for_queries(ds, db): # count, human_description_en and primary_keys are all table extras response = await ds.client.get("/data/-/query.declared?sql=select+*+from+dogs") assert response.status_code == 200 - assert response.json() == {"extras": {}, "num_rows": 3} + assert response.json() == {"page": {}, "num_rows": 3} @pytest.mark.asyncio @@ -97,13 +97,13 @@ async def test_row_renderer_omits_extras_not_available_for_rows(ds, db): assert response.status_code == 200 data = response.json() assert data["num_rows"] == 1 - extras = data["extras"] + page = data["page"] # count and human_description_en are not available for rows - assert "count" not in extras - assert "human_description_en" not in extras + assert "count" not in page + assert "human_description_en" not in page # Rows always include these - assert isinstance(extras.pop("query_ms"), float) - assert extras == { + assert isinstance(page.pop("query_ms"), float) + assert page == { "database": "data", "table": "dogs", "primary_keys": ["id"], @@ -144,7 +144,7 @@ async def test_row_renderer_omits_extras_not_available_for_rows(ds, db): async def test_renderer_receives_extras_requested_in_url(ds, db, path, expected): response = await ds.client.get(path) assert response.status_code == 200 - assert response.json()["extras"] == expected + assert response.json()["page"] == expected @pytest.mark.asyncio @@ -154,7 +154,7 @@ async def test_unknown_requested_extra_is_still_an_error(ds, db): @pytest.mark.asyncio -async def test_render_function_does_not_have_to_accept_extras(ds, db): +async def test_render_function_does_not_have_to_accept_page(ds, db): response = await ds.client.get("/data/dogs.noargument") assert response.status_code == 200 assert response.text == "ok" @@ -197,4 +197,4 @@ def test_json_renderer_uses_documented_arguments_only(ds): render, _ = ds.renderers["json"] parameters = set(inspect.signature(render).parameters) assert not parameters & {"data", "args"} - assert {"rows", "columns", "extras"} <= parameters + assert {"rows", "columns", "page"} <= parameters From 0f061d18214c2865819f698aa55981e2d9b6bdfc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:05:25 +0000 Subject: [PATCH 05/10] Streaming output renderers, CSV and TSV are now default renderers Output renderers can accept a new row_stream argument: an async iterator over the rows on the current page, or over every row of the table or view - fetched a page at a time - when the URL has ?_stream=1. Combined with Response.stream() this lets any format export a whole table. CSV and TSV are now implemented this way in datasette/csv_renderer.py, replacing stream_csv() and the special cases for those formats in the table, query and row views. Plugins can replace either of them. The three copies of the renderer dispatch code are now a single render_with_output_renderer() function, which also handles: - ?_dl=1 for every format, not just CSV and TSV - the max_csv_mb size limit, for any streamed response A streaming export that fails part of the way through, or reaches max_csv_mb, now drops the connection instead of writing the error as the last line of an otherwise complete looking file. New ?_extra=expanded_columns extra, used by the CSV renderer. Refs #2936, #1101, #1062 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 6 + datasette/csv_renderer.py | 160 ++++++++++++ datasette/plugins.py | 1 + datasette/renderer.py | 30 +++ datasette/templates/_export_dialog.html | 2 +- datasette/views/base.py | 307 +++++++++-------------- datasette/views/database.py | 53 +--- datasette/views/row.py | 47 +--- datasette/views/table.py | 95 +++---- datasette/views/table_extras.py | 14 ++ docs/changelog.rst | 6 + docs/csv_export.rst | 15 +- docs/json_api.rst | 15 +- docs/plugin_hooks.rst | 45 +++- docs/plugins.rst | 9 + docs/settings.rst | 8 +- tests/conftest.py | 1 - tests/fixtures.py | 6 - tests/test_csv.py | 28 --- tests/test_renderer_streaming.py | 314 ++++++++++++++++++++++++ 20 files changed, 788 insertions(+), 374 deletions(-) create mode 100644 datasette/csv_renderer.py create mode 100644 tests/test_renderer_streaming.py diff --git a/datasette/app.py b/datasette/app.py index 9d8fc6bb66..a7148f6e8e 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -591,6 +591,7 @@ def __init__( # File extension -> label, description, is_binary and is_webpage self._renderer_options = {} self._renderer_extras = {} # File extension -> extras the renderer declared + self._renderer_can_stream = {} # File extension -> accepts row_stream self.version_note = version_note if self.setting("num_sql_threads") == 0: self.executor = None @@ -2582,6 +2583,11 @@ def _register_renderers(self): f"Output renderer '{extension}' extras must be a list of strings" ) self._renderer_extras[extension] = list(declared_extras) + # Renderers that accept row_stream can stream every row + self._renderer_can_stream[extension] = ( + "row_stream" + in inspect.signature(self.renderers[extension][0]).parameters + ) # How the export dialog presents this format is_binary = bool(renderer.get("is_binary")) is_webpage = bool(renderer.get("is_webpage")) diff --git a/datasette/csv_renderer.py b/datasette/csv_renderer.py new file mode 100644 index 0000000000..b039e0c934 --- /dev/null +++ b/datasette/csv_renderer.py @@ -0,0 +1,160 @@ +import csv +import hashlib +import io + +import markupsafe + +from datasette import hookimpl +from datasette.utils import path_from_row_pks, path_with_format +from datasette.utils.asgi import Response +from datasette.views.base import DatasetteError + +# TSV uses Excel's tab-separated dialect, so it pastes cleanly into Excel and +# Google Sheets: values containing tabs, newlines or double quotes are wrapped +# in double quotes, with any double quotes inside them doubled. +FORMATS = { + # extension: (csv module dialect, content type used for downloads) + "csv": ("excel", "text/csv; charset=utf-8"), + "tsv": ("excel-tab", "text/tab-separated-values; charset=utf-8"), +} + + +def _blob_url(datasette, request, format_, database, table, pks, columns, row, column): + "URL that serves the binary content of this cell" + cell = row[columns.index(column)] + # If this is a table page with a way to identify the row, use + # .urls.row_blob(). Views usually have no rowid, so they use the + # content hash. + if table and (pks or "rowid" in columns): + return datasette.absolute_url( + request, + datasette.urls.row_blob( + database, table, path_from_row_pks(row, pks, not pks), column + ), + ) + # Otherwise generate URL for this query + return datasette.absolute_url( + request, + path_with_format( + request=request, + format="blob", + extra_qs={ + "_blob_column": column, + "_blob_hash": hashlib.sha256(cell).hexdigest(), + }, + replace_format=format_, + ), + ) + + +def render_delimited( + format_, datasette, request, columns, row_stream, database, table, page, error +): + if error: + raise DatasetteError(error, title="Invalid SQL", status=400) + + dialect, download_content_type = FORMATS[format_] + pks = page.get("primary_keys") or [] + # Columns expanded using ?_labels= get an additional column_label heading + expanded_columns = set(page.get("expanded_columns") or []) + headings = [] + for column in columns: + headings.append(column) + if column in expanded_columns: + headings.append(f"{column}_label") + + def cells(row): + for column, cell in zip(columns, row): + if isinstance(cell, bytes): + cell = _blob_url( + datasette, + request, + format_, + database, + table, + pks, + columns, + row, + column, + ) + if column not in expanded_columns: + yield cell + elif cell is None: + yield "" + yield "" + elif isinstance(cell, dict): + # {"value": ..., "label": ...} + yield cell["value"] + yield cell["label"] + else: + yield cell + yield "" + + # ?_trace=1 wraps the output in HTML so the trace can be shown below it + trace = request.args.get("_trace") + + async def body(): + buffer = io.StringIO() + writer = csv.writer(buffer, dialect=dialect) + + def written(): + value = buffer.getvalue() + buffer.seek(0) + buffer.truncate() + return str(markupsafe.escape(value)) if trace else value + + if trace: + yield ( + f"{format_.upper()} debug" + '" + + if trace: + content_type = "text/html; charset=utf-8" + elif request.args.get("_dl"): + content_type = download_content_type + else: + content_type = "text/plain; charset=utf-8" + return Response.stream(body(), content_type=content_type) + + +def render_csv(datasette, request, columns, row_stream, database, table, page, error): + return render_delimited( + "csv", datasette, request, columns, row_stream, database, table, page, error + ) + + +def render_tsv(datasette, request, columns, row_stream, database, table, page, error): + return render_delimited( + "tsv", datasette, request, columns, row_stream, database, table, page, error + ) + + +# tryfirst so that a plugin registering one of these extensions replaces it +@hookimpl(tryfirst=True) +def register_output_renderer(): + return [ + { + "extension": "tsv", + "render": render_tsv, + "extras": ["expanded_columns"], + "label": "TSV", + "description": "Tab-separated values, for pasting into Excel or Google Sheets", + }, + { + "extension": "csv", + "render": render_csv, + "extras": ["expanded_columns"], + "label": "CSV", + "description": "Comma-separated values, for spreadsheets and other tools", + }, + ] diff --git a/datasette/plugins.py b/datasette/plugins.py index 6a4d7da726..b8deddf92e 100644 --- a/datasette/plugins.py +++ b/datasette/plugins.py @@ -23,6 +23,7 @@ "datasette.default_column_types", "datasette.default_magic_parameters", "datasette.blob_renderer", + "datasette.csv_renderer", "datasette.default_debug_menu", "datasette.default_jump_items", "datasette.default_database_actions", diff --git a/datasette/renderer.py b/datasette/renderer.py index 30fa3bae0e..00d652f20a 100644 --- a/datasette/renderer.py +++ b/datasette/renderer.py @@ -10,6 +10,36 @@ from datasette.utils.asgi import Response +class RowStream: + """ + The row_stream argument passed to output renderers: an async iterator + over the rows to render. + + This is the rows on the current page, or every row - fetched a page at + a time - if the request asked for them all using ?_stream=1. + + Use ``async for row in row_stream`` to loop through individual rows, or + ``async for rows in row_stream.pages()`` for a list of rows at a time. + """ + + def __init__(self, rows, fetch_next_page=None): + self._rows = rows + self._fetch_next_page = fetch_next_page + + async def pages(self): + yield self._rows + while self._fetch_next_page is not None: + rows = await self._fetch_next_page() + if rows is None: + break + yield rows + + async def __aiter__(self): + async for rows in self.pages(): + for row in rows: + yield row + + def _load_json_value(value): try: return json.loads(value) diff --git a/datasette/templates/_export_dialog.html b/datasette/templates/_export_dialog.html index 7d8895ff4b..f528c120f8 100644 --- a/datasette/templates/_export_dialog.html +++ b/datasette/templates/_export_dialog.html @@ -121,7 +121,7 @@ {{ export_option("json-object", "JSON object", "Rows keyed by their primary key", append_querystring(renderers['json'], '_shape=object'), export_base ~ ".json", export_rows) }} {% endif %} {% endif %} - {% for name, url in renderers.items() if name != "json" %} + {% for name, url in renderers.items() if name not in ("json", "csv") and not (name == "tsv" and url_tsv_path) %} {% set options = (renderer_options or {}).get(name) or {} %} {{ 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)) }} {% endfor %} diff --git a/datasette/views/base.py b/datasette/views/base.py index 74b83f6637..61426bc0d5 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -1,21 +1,15 @@ -import csv -import hashlib -import sys +import asyncio from datasette.extras import extra_names_from_request +from datasette.renderer import RowStream from datasette.utils import ( - EscapeHtmlWriter, - InvalidSql, - LimitedWriter, add_cors_headers, - path_from_row_pks, + call_with_supported_arguments, path_with_format, - sqlite3, ) from datasette.utils.asgi import ( - AsgiStream, BadRequest, - Request, + NotFound, Response, ) @@ -198,193 +192,130 @@ def page_for_renderer(datasette, request, format_, data): } -# Formats that stream_csv() writes, with their content type for downloads. -# TSV uses Excel's tab-separated dialect, so it pastes cleanly into Excel and -# Google Sheets: values containing tabs, newlines or double quotes are wrapped -# in double quotes, with any double quotes inside them doubled. -CSV_FORMATS = { - "csv": ("excel", "text/csv; charset=utf-8"), - "tsv": ("excel-tab", "text/tab-separated-values; charset=utf-8"), -} - - -def is_csv_format(datasette, format_): - """True if stream_csv() should handle this format. A plugin that - registers its own tsv output renderer takes over .tsv from Datasette.""" - return format_ == "csv" or (format_ == "tsv" and "tsv" not in datasette.renderers) - - def tsv_export_path(datasette, request): """Path to this page as TSV, or None if a plugin handles .tsv instead""" - if not is_csv_format(datasette, "tsv"): + from datasette.csv_renderer import render_tsv + + if datasette.renderers.get("tsv", (None,))[0] is not render_tsv: return None # route_path is the path without base_url, set when base_url is not "/" path = request.scope.get("route_path") or request.path return datasette.urls.path(path_with_format(path=path, format="tsv")) -async def stream_csv(datasette, fetch_data, request, database, format_="csv"): - dialect, download_content_type = CSV_FORMATS[format_] - kwargs = {} - stream = request.args.get("_stream") - # Do not calculate facets or counts: - extra_parameters = [ - f"{key}=1" for key in ("_nofacet", "_nocount") if not request.args.get(key) - ] - if extra_parameters: - # Replace request object with a new one with modified scope - if not request.query_string: - new_query_string = "&".join(extra_parameters) - else: - new_query_string = request.query_string + "&" + "&".join(extra_parameters) - new_scope = dict(request.scope, query_string=new_query_string.encode("latin-1")) - receive = request.receive - request = Request(new_scope, receive) - if stream: - # Some quick soundness checks - if not datasette.setting("allow_csv_stream"): - raise BadRequest("CSV streaming is disabled") - if request.args.get("_next"): - raise BadRequest("_next not allowed for CSV streaming") - kwargs["_size"] = "max" - # Fetch the first page +def stream_requested(datasette, request, format_): + """ + True if this request should stream every row: it has ?_stream=1 and the + output renderer for this format can stream. Formats that cannot stream + ignore ?_stream=. + """ + if not request.args.get("_stream"): + return False + if not datasette._renderer_can_stream.get(format_): + return False + if not datasette.setting("allow_csv_stream"): + raise BadRequest("Streaming is disabled") + if request.args.get("_next"): + raise BadRequest("_next not allowed when streaming") + return True + + +class StreamSizeExceeded(Exception): + pass + + +async def _limit_stream_size(body, limit_mb): + limit_bytes = limit_mb * 1024 * 1024 + sent = 0 try: - response_or_template_contexts = await fetch_data(request) - if isinstance(response_or_template_contexts, Response): - return response_or_template_contexts - elif len(response_or_template_contexts) == 4: - data, _, _, _ = response_or_template_contexts - else: - data, _, _ = response_or_template_contexts - except (sqlite3.OperationalError, InvalidSql) as e: - raise DatasetteError(str(e), title="Invalid SQL", status=400) - - except DatasetteError: - raise - - # Convert rows and columns to CSV - headings = data["columns"] - # if there are expanded_columns we need to add additional headings - expanded_columns = set(data.get("expanded_columns") or []) - if expanded_columns: - headings = [] - for column in data["columns"]: - headings.append(column) - if column in expanded_columns: - headings.append(f"{column}_label") - - content_type = "text/plain; charset=utf-8" - preamble = "" - postamble = "" - - trace = request.args.get("_trace") - if trace: - content_type = "text/html; charset=utf-8" - preamble = ( - f"{format_.upper()} debug" - '" - - async def stream_fn(r): - nonlocal data, trace - limited_writer = LimitedWriter(r, datasette.setting("max_csv_mb")) - if trace: - await limited_writer.write(preamble) - writer = csv.writer(EscapeHtmlWriter(limited_writer), dialect=dialect) - else: - writer = csv.writer(limited_writer, dialect=dialect) - first = True - next = None - while first or (next and stream): - try: - kwargs = {} - if next: - kwargs["_next"] = next - if not first: - data, _, _ = await fetch_data(request, **kwargs) - if first: - if request.args.get("_header") != "off": - await writer.writerow(headings) - first = False - next = data.get("next") - for row in data["rows"]: - if any(isinstance(r, bytes) for r in row): - new_row = [] - for column, cell in zip(headings, row): - if isinstance(cell, bytes): - pks = data.get("primary_keys") or [] - # If this is a table page with a way to identify - # the row, use .urls.row_blob(). Views usually - # have no rowid, so they use the content hash. - if data.get("table") and (pks or "rowid" in headings): - cell = datasette.absolute_url( - request, - datasette.urls.row_blob( - database, - data["table"], - path_from_row_pks(row, pks, not pks), - column, - ), - ) - else: - # Otherwise generate URL for this query - url = datasette.absolute_url( - request, - path_with_format( - request=request, - format="blob", - extra_qs={ - "_blob_column": column, - "_blob_hash": hashlib.sha256( - cell - ).hexdigest(), - }, - replace_format=format_, - ), - ) - for internal_arg in ("_nocount=1", "_nofacet=1"): - url = url.replace("&" + internal_arg, "") - url = url.replace("?" + internal_arg + "&", "?") - cell = url - new_row.append(cell) - row = new_row - if not expanded_columns: - # Simple path - await writer.writerow(row) - else: - # Look for {"value": "label": } dicts and expand - new_row = [] - for heading, cell in zip(data["columns"], row): - if heading in expanded_columns: - if cell is None: - new_row.extend(("", "")) - else: - if not isinstance(cell, dict): - new_row.extend((cell, "")) - else: - new_row.append(cell["value"]) - new_row.append(cell["label"]) - else: - new_row.append(cell) - await writer.writerow(new_row) - except Exception as ex: # noqa: BLE001 - # Streaming CSV: report the error into the response body and stop - sys.stderr.write(f"Caught this error: {ex}\n") - sys.stderr.flush() - await r.write(str(ex)) - return - await limited_writer.write(postamble) - - headers = {} - if datasette.cors: - add_cors_headers(headers) - if request.args.get("_dl", None): - if not trace: - content_type = download_content_type - disposition = 'attachment; filename="{}.{}"'.format( - request.url_vars.get("table", database), format_ + elif isinstance(result, Response): + response = result + else: + assert False, f"{result} should be dict or Response" + + # ?_dl=1 downloads the response as a file + if ( + request.args.get("_dl") + and response.status == 200 + and not any(key.lower() == "content-disposition" for key in response.headers) + ): + filename = request.url_vars.get("table", database) + response.headers["content-disposition"] = ( + f'attachment; filename="{filename}.{format_}"' ) - headers["content-disposition"] = disposition - return AsgiStream(stream_fn, headers=headers, content_type=content_type) + # Streamed responses are limited in size + limit_mb = datasette.setting("max_csv_mb") + if limit_mb and hasattr(response.body, "__aiter__"): + response.body = _limit_stream_size(response.body, limit_mb) + return response diff --git a/datasette/views/database.py b/datasette/views/database.py index f54b86cce5..8fd6919d4d 100644 --- a/datasette/views/database.py +++ b/datasette/views/database.py @@ -1,4 +1,3 @@ -import asyncio import hashlib import itertools import json @@ -50,9 +49,7 @@ from .base import ( DatasetteError, View, - is_csv_format, - page_for_renderer, - stream_csv, + render_with_output_renderer, tsv_export_path, ) from .query_helpers import ( @@ -900,20 +897,7 @@ async def query_metadata(): return await datasette.get_database_metadata(database) # Handle formats from plugins - if is_csv_format(datasette, format_): - if not sql: - raise DatasetteError("?sql= is required", status=400) - - async def fetch_data_for_csv(request, _next=None): - # Reuse the trusted magic parameter values prepared above. - results = await db.execute(sql, params_for_query, truncate=True) - data = {"rows": results.rows, "columns": results.columns} - return data, None, None - - return await stream_csv( - datasette, fetch_data_for_csv, request, db.name, format_=format_ - ) - elif format_ in datasette.renderers: + if format_ in datasette.renderers: if not sql: raise DatasetteError("?sql= is required", status=400) data = {"ok": True, "rows": rows, "columns": columns} @@ -938,44 +922,21 @@ async def fetch_data_for_csv(request, _next=None): extra_registry=table_extra_registry, ) data.update(await resolve_query_extras(extras, query_extra_context)) - # Dispatch request to the correct output format renderer - # (CSV is not handled here due to streaming) - result = call_with_supported_arguments( - datasette.renderers[format_][0], - datasette=datasette, + r = await render_with_output_renderer( + datasette, + request, + format_, + data=data, columns=columns, rows=rows, sql=sql, query_name=stored_query.name if stored_query else None, database=database, table=None, - request=request, view_name="table", truncated=results.truncated if results else False, error=query_error, - page=page_for_renderer(datasette, request, format_, data), - # These will be deprecated in Datasette 1.0: - args=request.args, - data=data, ) - if asyncio.iscoroutine(result): - result = await result - if result is None: - raise NotFound("No data") - if isinstance(result, dict): - r = Response( - body=result.get("body"), - status=result.get("status_code") or 200, - content_type=result.get("content_type", "text/plain"), - headers=result.get("headers"), - ) - elif isinstance(result, Response): - r = result - # if status_code is not None: - # # Over-ride the status code - # r.status = status_code - else: - assert False, f"{result} should be dict or Response" elif format_ == "html": headers = {} templates = [f"query-{to_css_class(database)}.html", "query.html"] diff --git a/datasette/views/row.py b/datasette/views/row.py index 32e2c944c7..71d4aa9803 100644 --- a/datasette/views/row.py +++ b/datasette/views/row.py @@ -38,9 +38,7 @@ from .base import ( BaseView, DatasetteError, - is_csv_format, - page_for_renderer, - stream_csv, + render_with_output_renderer, tsv_export_path, ) from .table import ( @@ -176,19 +174,12 @@ def redirect(self, request, path, forward_querystring=True, remove_args=None): add_cors_headers(response.headers) return response - async def as_csv(self, request, database, format_="csv"): - return await stream_csv(self.ds, self.data, request, database, format_=format_) - async def get(self, request): db = await self.ds.resolve_database(request) database = db.name - database_route = db.route format_ = request.url_vars.get("format") or "html" data_kwargs = {} - if is_csv_format(self.ds, format_): - return await self.as_csv(request, database_route, format_=format_) - if format_ == "html": # HTML views default to expanding all foreign key labels data_kwargs["default_labels"] = True @@ -243,44 +234,24 @@ async def get(self, request): data["query_ms"] = (end - start) * 1000 if format_ in self.ds.renderers: - # Dispatch request to the correct output format renderer - # (CSV is not handled here due to streaming) - result = call_with_supported_arguments( - self.ds.renderers[format_][0], - datasette=self.ds, + response = await render_with_output_renderer( + self.ds, + request, + format_, + data=data, columns=data.get("columns") or [], rows=data.get("rows") or [], sql=data.get("query", {}).get("sql", None), query_name=data.get("query_name"), database=database, table=data.get("table"), - request=request, view_name=self.name, truncated=False, # TODO: support this error=data.get("error"), - page=page_for_renderer(self.ds, request, format_, data), - # These will be deprecated in Datasette 1.0: - args=request.args, - data=data, ) - if asyncio.iscoroutine(result): - result = await result - if result is None: - raise NotFound("No data") - if isinstance(result, dict): - response = Response( - body=result.get("body"), - status=result.get("status_code", status_code or 200), - content_type=result.get("content_type", "text/plain"), - headers=result.get("headers"), - ) - elif isinstance(result, Response): - response = result - if status_code is not None: - # Over-ride the status code - response.status = status_code - else: - assert False, f"{result} should be dict or Response" + if status_code is not None: + # Over-ride the status code + response.status = status_code elif format_ == "html": response = await self.html(request, data, extra_template_data, templates) if status_code is not None: diff --git a/datasette/views/table.py b/datasette/views/table.py index 9fb00f2f04..4e51fb641f 100644 --- a/datasette/views/table.py +++ b/datasette/views/table.py @@ -1,4 +1,3 @@ -import asyncio import hashlib import itertools import json @@ -32,7 +31,6 @@ add_cors_headers, append_querystring, await_me_maybe, - call_with_supported_arguments, compound_keys_after_sql, compound_keys_at_or_before_sql, decode_write_json_rows, @@ -68,9 +66,8 @@ from .base import ( BaseView, DatasetteError, - is_csv_format, - page_for_renderer, - stream_csv, + render_with_output_renderer, + stream_requested, tsv_export_path, ) from .database import QueryView @@ -1997,73 +1994,44 @@ async def table_view_traced(datasette, request): data, rows, columns, _expanded_columns, sql, next_url = view_data # Handle formats from plugins - if is_csv_format(datasette, format_): - - async def fetch_data(request, _next=None): - ( - data, - rows, - columns, - expanded_columns, - _sql, - _next_url, - ) = await table_view_data( + if format_ in datasette.renderers: + next_token = data["next"] + + async def fetch_next_page(): + # Used to stream every row, a page at a time + nonlocal next_token + if not next_token: + return None + page_data, page_rows, *_ = await table_view_data( datasette, request, resolved, - extra_extras=extra_extras, - context_for_html_hack=context_for_html_hack, default_labels=default_labels, - _next=_next, + _next=next_token, + rows_only=True, ) - data["rows"] = rows - data["table"] = resolved.table - data["columns"] = columns - data["expanded_columns"] = expanded_columns - return data, None, None - - return await stream_csv( - datasette, fetch_data, request, resolved.db.name, format_=format_ - ) - elif format_ in datasette.renderers: - # Dispatch request to the correct output format renderer - # (CSV is not handled here due to streaming) - result = call_with_supported_arguments( - datasette.renderers[format_][0], - datasette=datasette, + next_token = page_data["next"] + return page_rows + + r = await render_with_output_renderer( + datasette, + request, + format_, + data=data, columns=columns, rows=rows, sql=sql, query_name=None, database=resolved.db.name, table=resolved.table, - request=request, view_name="table", truncated=False, error=None, - page=page_for_renderer(datasette, request, format_, data), - # These will be deprecated in Datasette 1.0: - args=request.args, - data=data, + fetch_next_page=fetch_next_page, ) - if asyncio.iscoroutine(result): - result = await result - if result is None: - raise NotFound("No data") - if isinstance(result, dict): - r = Response( - body=result.get("body"), - status=result.get("status_code") or 200, - content_type=result.get("content_type", "text/plain"), - headers=result.get("headers"), - ) - elif isinstance(result, Response): - r = result - # if status_code is not None: - # # Over-ride the status code - # r.status = status_code - else: - assert False, f"{result} should be dict or Response" + if stream_requested(datasette, request, format_): + # Every row is in this response, so there is no next page + next_url = None elif format_ == "html": headers = {} templates = [ @@ -2380,6 +2348,7 @@ async def table_view_data( default_labels=False, _next=None, renderer_extras=None, + rows_only=False, ): extra_extras = extra_extras or set() # We have a table or view @@ -2616,6 +2585,17 @@ async def table_view_data( ) rows = rows[:page_size] + if rows_only: + # A later page of a streaming response: skip the extras + return ( + {"next": next_value and str(next_value) or None}, + rows, + columns, + expanded_columns, + sql, + next_url, + ) + # Resolve extras extras = extra_names_from_request(request) if not extra_extras: @@ -2657,6 +2637,7 @@ async def table_view_data( private=private, rows=rows, columns=columns, + expanded_columns=expanded_columns, results_description=results.description, table_columns=table_columns, pks=pks, diff --git a/datasette/views/table_extras.py b/datasette/views/table_extras.py index befb558c45..54cd806e42 100644 --- a/datasette/views/table_extras.py +++ b/datasette/views/table_extras.py @@ -30,6 +30,7 @@ class TableExtraContext: private: bool rows: list columns: list + expanded_columns: list results_description: list table_columns: list pks: list @@ -1193,6 +1194,18 @@ async def resolve(self, context): return expandables +class ExpandedColumnsExtra(Extra): + description = 'List of foreign key columns that have been expanded with labels on this page, using ``?_labels=on`` or ``?_label=column``. Values in those columns are returned as ``{"value": ..., "label": ...}`` objects.' + docs_note = "See :ref:`expand_foreign_keys` for how to expand these labels." + example = ExtraExample( + "/fixtures/facetable.json?_labels=on&_extra=expanded_columns" + ) + scopes: ClassVar[set[ExtraScope]] = {ExtraScope.TABLE} + + async def resolve(self, context): + return list(context.expanded_columns) + + class ForeignKeyTablesExtra(Extra): description = "List of tables that link to this row using foreign keys. Each item includes the foreign key fields plus ``count`` for matching rows and ``link`` for the filtered table URL." example = ExtraExample( @@ -1347,6 +1360,7 @@ async def resolve(self, context): IsViewExtra, PrivateExtra, ExpandableColumnsExtra, + ExpandedColumnsExtra, ForeignKeyTablesExtra, FormHiddenArgsExtra, ] diff --git a/docs/changelog.rst b/docs/changelog.rst index ce461d95fd..5a469f29b8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,12 @@ Unreleased ---------- - 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`. +- 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`) +- 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`) +- **Breaking change**: an "include all rows" export that fails part of the way through, or that reaches the :ref:`setting_max_csv_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. +- ``?_dl=1`` now adds a ``content-disposition: attachment`` header for every export format, not only CSV and TSV. +- New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``. +- ``csv`` and ``tsv`` are now included in the ``?_extra=renderers`` extra. - Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras ` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function in a new ``page`` argument, a dictionary which also includes ``next`` and ``next_url`` on table pages. (:issue:`2770`, :issue:`2186`) - The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests. - Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ```` element for that name matched a class used by Datasette's own CSS and JavaScript. diff --git a/docs/csv_export.rst b/docs/csv_export.rst index afb6359bef..9d307a87d9 100644 --- a/docs/csv_export.rst +++ b/docs/csv_export.rst @@ -91,7 +91,7 @@ by Datasette. Stream all matching records, not just the first page of results. See below. ``?_dl=on`` - Causes Datasette to return a ``content-disposition: attachment; filename="filename.csv"`` header, or ``filename.tsv`` for TSV. + Causes Datasette to return a ``content-disposition: attachment; filename="filename.csv"`` header, or ``filename.tsv`` for TSV. This works for every other export format too. Streaming all records --------------------- @@ -101,10 +101,15 @@ under the hood it takes advantage of Python 3 asyncio capabilities and Datasette's efficient :ref:`pagination ` to stream back the full CSV or TSV file. -Since databases can get pretty large, by default this option is capped at 100MB - -if a table returns more than 100MB of data the last line of the file will be a -truncation error message. +Since databases can get pretty large, by default this option is capped at 100MB. +If a table returns more than 100MB of data Datasette stops and drops the +connection, so the download fails instead of saving a file that is silently +missing rows. The same thing happens if an error occurs part of the way through. You can increase or remove this limit using the :ref:`setting_max_csv_mb` config -setting. You can also disable the CSV export feature entirely using +setting. You can also disable the *include all rows* option entirely using :ref:`setting_allow_csv_stream`. + +CSV and TSV are implemented as :ref:`output renderers ` +that stream their rows. Plugins can add other formats that work the same way, see +:ref:`plugin_register_output_renderer_streaming`. diff --git a/docs/json_api.rst b/docs/json_api.rst index 80ce712a07..8708919fb4 100644 --- a/docs/json_api.rst +++ b/docs/json_api.rst @@ -757,7 +757,9 @@ The available table extras are listed below. .. code-block:: json { - "json": "/fixtures/facetable.json?_extra=renderers&_format=json&_labels=on" + "json": "/fixtures/facetable.json?_extra=renderers&_format=json&_labels=on", + "tsv": "/fixtures/facetable.json?_extra=renderers&_format=tsv&_labels=on", + "csv": "/fixtures/facetable.json?_extra=renderers&_format=csv&_labels=on" } ``custom_table_templates`` @@ -869,6 +871,17 @@ The available table extras are listed below. ] ] +``expanded_columns`` + List of foreign key columns that have been expanded with labels on this page, using ``?_labels=on`` or ``?_label=column``. Values in those columns are returned as ``{"value": ..., "label": ...}`` objects. (See :ref:`expand_foreign_keys` for how to expand these labels.) + + ``GET /fixtures/facetable.json?_labels=on&_extra=expanded_columns`` + + .. code-block:: json + + [ + "_city_id" + ] + ``form_hidden_args`` List of ``(name, value)`` pairs for hidden form fields used by the HTML table interface to preserve current query string options. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 9d35640579..95e44802e6 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -662,7 +662,10 @@ When a request is received, the ``"render"`` callback function is called with ze The names of the columns returned by this query. ``rows`` - list of ``sqlite3.Row`` objects - The rows returned by the query. + The rows returned by the query. For a table this is the rows on the current page. + +``row_stream`` - async iterator + An async iterator over the rows to render. This is the rows on the current page, or every row if the request has ``?_stream=1``. See :ref:`plugin_register_output_renderer_streaming`. ``sql`` - string The SQL query that was executed. @@ -745,6 +748,46 @@ And here is an example ``can_render`` function which returns ``True`` only if th Examples: `datasette-atom `_, `datasette-ics `_, `datasette-geojson `__, `datasette-copyable `__ + +.. _plugin_register_output_renderer_streaming: + +Streaming every row +~~~~~~~~~~~~~~~~~~~ + +A table can have far more rows than fit on one page. A ``"render"`` function that accepts the ``row_stream`` argument can output all of them, without loading them all into memory, by returning a :ref:`streaming response `: + +.. code-block:: python + + import json + + + def render_ndjson(columns, row_stream): + async def body(): + async for row in row_stream: + yield json.dumps(dict(zip(columns, row))) + "\n" + + return Response.stream( + body(), content_type="application/x-ndjson" + ) + + + @hookimpl + def register_output_renderer(datasette): + return {"extension": "ndjson", "render": render_ndjson} + +``row_stream`` yields the rows on the current page. If the URL includes ``?_stream=1`` it carries on past the end of that page, fetching one page at a time, until it has yielded every row in the table or view. Your function does not need to know which of those is happening. + +Use ``async for rows in row_stream.pages()`` to receive a list of rows for each page instead of one row at a time. + +Datasette's own :ref:`CSV and TSV export ` is implemented this way. Some things to be aware of: + +- ``?_stream=1`` is ignored by formats that do not accept ``row_stream``. +- Only tables and views have more than one page. For a row, or the results of a SQL query, ``row_stream`` yields the same rows as ``rows``. +- ``rows``, ``page`` and the other arguments describe the first page. Everything that could result in an error page - an invalid filter, a permission check - has already happened by the time your function is called. +- :ref:`setting_allow_csv_stream` and :ref:`setting_max_csv_mb` apply to every format, not only CSV. A streamed response that grows larger than ``max_csv_mb`` is cut off by dropping the connection, as described in :ref:`internals_response_stream`. + +Any format can be downloaded as a file by adding ``?_dl=1`` to the URL, which adds a ``content-disposition: attachment`` header with a filename ending in the format's extension. A response that sets its own ``content-disposition`` header is left alone. + .. _plugin_register_routes: register_routes(datasette) diff --git a/docs/plugins.rst b/docs/plugins.rst index e7c5323307..2cd34bff0c 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -198,6 +198,15 @@ If you run ``datasette plugins --all`` it will include default plugins that ship "register_output_renderer" ] }, + { + "name": "datasette.csv_renderer", + "static": false, + "templates": false, + "version": null, + "hooks": [ + "register_output_renderer" + ] + }, { "name": "datasette.default_actions", "static": false, diff --git a/docs/settings.rst b/docs/settings.rst index d123f31cb0..13e6f4b6f1 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -421,7 +421,9 @@ Default: ``on`` Enables :ref:`the CSV and TSV export feature ` where an entire table (potentially hundreds of thousands of rows) can be exported as a single -CSV or TSV file. You can turn it off like this: +CSV or TSV file. It also controls ``?_stream=1`` for any other +:ref:`output format that can stream `. +You can turn it off like this: :: @@ -440,7 +442,9 @@ Default: ``100`` .. [[[end]]] -The maximum size of CSV or TSV that can be exported, in megabytes. +The maximum size of CSV or TSV that can be exported, in megabytes. The limit +applies to any other :ref:`output format that streams its response ` +as well. An export that reaches the limit is cut off by dropping the connection. You can disable the limit entirely by setting this to 0: :: diff --git a/tests/conftest.py b/tests/conftest.py index a5c2b39253..07b25ee7ed 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -425,7 +425,6 @@ def start(plugins, *extra_args, wait_for_startup=True): app_client, app_client_base_url_prefix, app_client_conflicting_database_names, - app_client_csv_max_mb_one, app_client_immutable_and_inspect_file, app_client_larger_cache_size, app_client_no_files, diff --git a/tests/fixtures.py b/tests/fixtures.py index f8710ad4c2..07034f5dd8 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -253,12 +253,6 @@ def app_client_larger_cache_size(): yield client -@pytest.fixture(scope="session") -def app_client_csv_max_mb_one(): - with make_app_client(settings={"max_csv_mb": 1}) as client: - yield client - - @pytest.fixture(scope="session") def app_client_with_dot(): with make_app_client(filename="fixtures.dot.db") as client: diff --git a/tests/test_csv.py b/tests/test_csv.py index 724454cadd..e8caefe8e1 100644 --- a/tests/test_csv.py +++ b/tests/test_csv.py @@ -260,34 +260,6 @@ async def test_csv_with_non_ascii_characters(ds_client): assert response.text == "text,number\r\n𝐜𝐢𝐭𝐢𝐞𝐬,1\r\nbob,2\r\n" -@pytest.mark.xfail(reason="Flaky, see https://github.com/simonw/datasette/issues/2355") -def test_max_csv_mb(app_client_csv_max_mb_one): - # This query deliberately generates a really long string - # should be 100*100*100*2 = roughly 2MB - response = app_client_csv_max_mb_one.get( - "/fixtures.csv?" - + urllib.parse.urlencode( - { - "sql": """ - select group_concat('ab', '') - from json_each(json_array({lots})), - json_each(json_array({lots})), - json_each(json_array({lots})) - """.format( - lots=", ".join(str(i) for i in range(100)) - ), - "_stream": 1, - "_size": "max", - } - ), - ) - # It's a 200 because we started streaming before we knew the error - assert response.status == 200 - # Last line should be an error message - last_line = [line for line in response.body.split(b"\r\n") if line][-1] - assert last_line.startswith(b"CSV contains more than") - - @pytest.mark.asyncio async def test_table_csv_stream(ds_client): # Without _stream should return header + 100 rows: diff --git a/tests/test_renderer_streaming.py b/tests/test_renderer_streaming.py new file mode 100644 index 0000000000..2597630304 --- /dev/null +++ b/tests/test_renderer_streaming.py @@ -0,0 +1,314 @@ +""" +Output renderers that accept a row_stream argument can stream every row +when the request has ?_stream=1. The default CSV and TSV renderers in +datasette/csv_renderer.py are built on this. +""" + +import json + +import pytest +import pytest_asyncio + +from datasette import hookimpl +from datasette.app import Datasette +from datasette.plugins import pm +from datasette.utils.asgi import Response +from datasette.views.base import StreamSizeExceeded + + +class _StreamingRendererPlugin: + __name__ = "StreamingRendererPlugin" + + @hookimpl + def register_output_renderer(self): + def render_ndjson(columns, row_stream): + async def body(): + async for row in row_stream: + yield json.dumps(dict(zip(columns, row))) + "\n" + + return Response.stream(body(), content_type="application/x-ndjson") + + def render_page_sizes(row_stream): + async def body(): + async for rows in row_stream.pages(): + yield f"{len(rows)}\n" + + return Response.stream(body()) + + def render_big(row_stream): + async def body(): + async for _ in row_stream: + yield "x" * 1024 * 600 + + return Response.stream(body()) + + def render_not_streaming(rows): + return Response.text(str(len(rows))) + + def render_own_disposition(): + return Response.text( + "x", headers={"Content-Disposition": 'attachment; filename="mine.txt"'} + ) + + return [ + {"extension": "ndjson", "render": render_ndjson}, + {"extension": "pagesizes", "render": render_page_sizes}, + {"extension": "big", "render": render_big}, + {"extension": "notstreaming", "render": render_not_streaming}, + {"extension": "owndisposition", "render": render_own_disposition}, + ] + + +def _make_datasette(**settings): + return Datasette(memory=True, settings={"default_page_size": 10, **settings}) + + +@pytest.fixture +def plugin(): + pm.register(_StreamingRendererPlugin(), name="streaming_renderer") + try: + yield + finally: + pm.unregister(name="streaming_renderer") + + +async def _add_numbers(ds): + db = ds.add_memory_database("renderer_streaming_test", name="data") + await db.execute_write_script(""" + drop view if exists numbers_view; + drop table if exists numbers; + create table numbers (id integer primary key, name text); + insert into numbers (id, name) + select value, 'n' || (100 - value) from json_each( + '[' || ( + with recursive c(x) as (select 1 union all select x + 1 from c where x < 35) + select group_concat(x) from c + ) || ']' + ); + create view numbers_view as select * from numbers; + """) + return db + + +@pytest_asyncio.fixture +async def ds(plugin): + ds = _make_datasette() + await _add_numbers(ds) + try: + yield ds + finally: + ds.close() + + +def _ids(response): + return [json.loads(line)["id"] for line in response.text.splitlines()] + + +@pytest.mark.asyncio +async def test_row_stream_is_the_current_page_by_default(ds): + response = await ds.client.get("/data/numbers.ndjson") + assert response.status_code == 200 + assert response.headers["content-type"] == "application/x-ndjson" + assert _ids(response) == list(range(1, 11)) + # There is a next page + assert "_next=10" in response.headers["link"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("table", ("numbers", "numbers_view")) +async def test_row_stream_is_every_row_with_stream(ds, table): + response = await ds.client.get(f"/data/{table}.ndjson?_stream=1") + assert response.status_code == 200 + assert _ids(response) == list(range(1, 36)) + # Every row is in the response, so no next page is advertised + assert "link" not in response.headers + + +@pytest.mark.asyncio +async def test_row_stream_respects_filters_and_sort(ds): + response = await ds.client.get( + "/data/numbers.ndjson?_stream=1&id__gt=5&_sort_desc=name" + ) + ids = _ids(response) + assert sorted(ids) == list(range(6, 36)) + # name is 'n' || (100 - id) so descending name is ascending id + assert ids == list(range(6, 36)) + + +@pytest.mark.asyncio +async def test_row_stream_pages(ds): + response = await ds.client.get("/data/numbers.pagesizes?_stream=1") + assert response.text.split() == ["10", "10", "10", "5"] + response = await ds.client.get("/data/numbers.pagesizes?_stream=1&_size=20") + assert response.text.split() == ["20", "15"] + response = await ds.client.get("/data/numbers.pagesizes") + assert response.text.split() == ["10"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,expected", + ( + ("/data/numbers/3.ndjson?_stream=1", [3]), + ( + "/data/-/query.ndjson?sql=select+id,name+from+numbers+limit+12&_stream=1", + list(range(1, 13)), + ), + ), +) +async def test_row_stream_on_row_and_query_pages(ds, path, expected): + response = await ds.client.get(path) + assert response.status_code == 200 + assert _ids(response) == expected + + +@pytest.mark.asyncio +async def test_stream_ignored_by_renderers_that_do_not_accept_row_stream(ds): + response = await ds.client.get("/data/numbers.notstreaming?_stream=1") + assert response.status_code == 200 + assert response.text == "10" + # ... including the JSON renderer + response = await ds.client.get("/data/numbers.json?_stream=1") + assert len(response.json()["rows"]) == 10 + + +@pytest.mark.asyncio +async def test_stream_and_next_cannot_be_combined(ds): + response = await ds.client.get("/data/numbers.ndjson?_stream=1&_next=10") + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_streaming_can_be_disabled(plugin): + ds = _make_datasette(allow_csv_stream=False) + await _add_numbers(ds) + try: + for format_ in ("ndjson", "csv", "tsv"): + response = await ds.client.get(f"/data/numbers.{format_}?_stream=1") + assert response.status_code == 400, format_ + # Without ?_stream=1 it still works + response = await ds.client.get("/data/numbers.ndjson") + assert _ids(response) == list(range(1, 11)) + finally: + ds.close() + + +@pytest.mark.asyncio +async def test_streamed_response_larger_than_max_csv_mb_is_aborted(plugin): + ds = _make_datasette(max_csv_mb=1) + await _add_numbers(ds) + try: + # Under the limit: one row is 600KB + response = await ds.client.get("/data/numbers.big?_size=1") + assert response.status_code == 200 + assert len(response.content) == 1024 * 600 + # Over the limit: the response has already started, so it cannot + # become an error page - the connection is dropped instead + with pytest.raises(StreamSizeExceeded, match="max_csv_mb"): + await ds.client.get("/data/numbers.big?_size=2") + with pytest.raises(StreamSizeExceeded): + await ds.client.get( + "/data/-/query.csv?sql=select+printf('%.*c',+2000000,+'x')" + ) + finally: + ds.close() + + +@pytest.mark.asyncio +async def test_max_csv_mb_zero_disables_the_limit(plugin): + ds = _make_datasette(max_csv_mb=0) + await _add_numbers(ds) + try: + response = await ds.client.get("/data/numbers.big?_size=3") + assert len(response.content) == 3 * 1024 * 600 + finally: + ds.close() + + +@pytest.mark.asyncio +async def test_error_fetching_a_later_page_aborts_the_response(ds, monkeypatch): + from datasette.views import table + + original = table.table_view_data + calls = [] + + async def broken_on_third_page(*args, **kwargs): + calls.append(kwargs.get("_next")) + if len(calls) == 3: + raise ValueError("database went away") + return await original(*args, **kwargs) + + monkeypatch.setattr(table, "table_view_data", broken_on_third_page) + with pytest.raises(ValueError, match="database went away"): + await ds.client.get("/data/numbers.csv?_stream=1") + assert calls == [None, "10", "20"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,expected", + ( + ("/data/numbers.ndjson?_dl=1", 'attachment; filename="numbers.ndjson"'), + ("/data/numbers.json?_dl=1", 'attachment; filename="numbers.json"'), + ("/data/numbers/3.tsv?_dl=1", 'attachment; filename="numbers.tsv"'), + ( + "/data/-/query.ndjson?sql=select+1+as+id&_dl=1", + 'attachment; filename="data.ndjson"', + ), + # A renderer that sets its own header keeps it + ("/data/numbers.owndisposition?_dl=1", 'attachment; filename="mine.txt"'), + ("/data/numbers.ndjson", None), + # Errors are not downloads + ("/data/-/query.json?sql=select+nope&_dl=1", None), + ), +) +async def test_dl_downloads_any_format(ds, path, expected): + response = await ds.client.get(path) + assert response.headers.get("content-disposition") == expected + + +@pytest.mark.asyncio +async def test_plugin_can_replace_the_csv_renderer(): + class CsvPlugin: + __name__ = "CsvPlugin" + + @hookimpl + def register_output_renderer(self): + return { + "extension": "csv", + "render": lambda: Response.text("from the plugin"), + } + + pm.register(CsvPlugin(), name="csv_plugin") + try: + ds = Datasette(memory=True) + response = await ds.client.get("/_memory/-/query.csv?sql=select+1") + assert response.text == "from the plugin" + # TSV is still the default renderer + response = await ds.client.get("/_memory/-/query.tsv?sql=select+1+as+one") + assert response.text == "one\r\n1\r\n" + ds.close() + finally: + pm.unregister(name="csv_plugin") + + +@pytest.mark.asyncio +async def test_csv_and_tsv_are_registered_renderers(ds): + assert {"csv", "tsv", "json"} <= set(ds.renderers) + data = (await ds.client.get("/data/numbers.json?_extra=renderers")).json() + assert {"csv", "tsv", "json"} <= set(data["renderers"]) + + +@pytest.mark.asyncio +async def test_expanded_columns_extra(ds_client): + data = ( + await ds_client.get( + "/fixtures/facetable.json?_labels=on&_extra=expanded_columns&_size=1" + ) + ).json() + assert data["expanded_columns"] == ["_city_id"] + assert data["rows"][0]["_city_id"] == {"value": 1, "label": "San Francisco"} + data = ( + await ds_client.get("/fixtures/facetable.json?_extra=expanded_columns&_size=1") + ).json() + assert data["expanded_columns"] == [] From 32c49b4b1c706a638e48caed67762c7428257371 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:16:52 +0000 Subject: [PATCH 06/10] Setting aliases, rename allow_csv_stream and max_csv_mb New SETTING_ALIASES mechanism: a setting that has been renamed keeps working under its previous name in config files, the settings= parameter, --setting on the command line, datasette.setting() and the settings dictionary passed to templates. Previous names are not listed in --help-settings or /-/settings and are not documented. Setting both names at once is a startup error. Used to rename allow_csv_stream to allow_stream and max_csv_mb to max_stream_mb, since they now apply to every output format that streams. Also: - Removed OBSOLETE_SETTINGS, which nothing read. - Fixed a TypeError if the same setting was in both the config settings and the settings= parameter. Refs #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 55 +++++++--- datasette/cli.py | 3 + datasette/templates/_export_dialog.html | 4 +- datasette/views/base.py | 6 +- docs/changelog.rst | 3 +- docs/cli-reference.rst | 8 +- docs/csv_export.rst | 4 +- docs/plugin_hooks.rst | 2 +- docs/settings.rst | 20 ++-- tests/test_api.py | 4 +- tests/test_internals_datasette.py | 3 + tests/test_renderer_streaming.py | 12 +- tests/test_setting_aliases.py | 140 ++++++++++++++++++++++++ 13 files changed, 220 insertions(+), 44 deletions(-) create mode 100644 tests/test_setting_aliases.py diff --git a/datasette/app.py b/datasette/app.py index a7148f6e8e..6ddb3ab4a1 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -273,14 +273,14 @@ class PermissionCheck: ), Setting("cache_size_kb", 0, "SQLite cache size in KB (0 == use SQLite default)"), Setting( - "allow_csv_stream", + "allow_stream", True, - "Allow .csv?_stream=1 to download all rows (ignoring max_returned_rows)", + "Allow ?_stream=1 to export all rows (ignoring max_returned_rows)", ), Setting( - "max_csv_mb", + "max_stream_mb", 100, - "Maximum size allowed for CSV export in MB - set 0 to disable this limit", + "Maximum size allowed for a streamed export in MB - set 0 to disable this limit", ), Setting( "truncate_cells_html", @@ -304,12 +304,30 @@ class PermissionCheck: ), Setting("base_url", "/", "Datasette URLs should use this base path"), ) -_HASH_URLS_REMOVED = "The hash_urls setting has been removed, try the datasette-hashed-urls plugin instead" -OBSOLETE_SETTINGS = { - "hash_urls": _HASH_URLS_REMOVED, - "default_cache_ttl_hashed": _HASH_URLS_REMOVED, -} DEFAULT_SETTINGS = {option.name: option.default for option in SETTINGS} +# Previous names of settings that have been renamed, mapped to their new +# names. The old names are not documented but still work everywhere a +# setting can be set or read. +SETTING_ALIASES = { + "allow_csv_stream": "allow_stream", + "max_csv_mb": "max_stream_mb", +} + + +def resolve_setting_aliases(settings, source): + """ + Return a copy of the settings dictionary with any old setting names + replaced by their new names. source says where the settings came from, + for the error raised if a setting is given under both of its names. + """ + for old_name, name in SETTING_ALIASES.items(): + if old_name in settings and name in settings: + raise StartupError( + f"Setting '{name}' and its previous name '{old_name}' " + f"are both set in {source}" + ) + return {SETTING_ALIASES.get(key, key): value for key, value in settings.items()} + FAVICON_PATH = app_root / "datasette" / "static" / "favicon.png" @@ -551,7 +569,9 @@ def __init__( config = json.loads((config_dir / "datasette.json").read_text()) config = config or {} - config_settings = config.get("settings") or {} + config_settings = resolve_setting_aliases( + config.get("settings") or {}, "config file" + ) # Validate settings from config file for key, value in config_settings.items(): @@ -571,6 +591,7 @@ def __init__( # Validate settings from constructor parameter if settings: + settings = resolve_setting_aliases(settings, "settings parameter") for key, value in settings.items(): if key not in DEFAULT_SETTINGS: raise StartupError(f"Invalid setting '{key}' in settings parameter") @@ -586,7 +607,11 @@ def __init__( self.config = config # CLI settings should overwrite datasette.json settings - self._settings = dict(DEFAULT_SETTINGS, **(config_settings), **(settings or {})) + self._settings = { + **DEFAULT_SETTINGS, + **config_settings, + **(settings or {}), + } self.renderers = {} # File extension -> (renderer, can_render) functions # File extension -> label, description, is_binary and is_webpage self._renderer_options = {} @@ -1010,11 +1035,15 @@ def close(self): raise first_exception def setting(self, key): - return self._settings.get(key, None) + return self._settings.get(SETTING_ALIASES.get(key, key), None) def settings_dict(self): # Returns a fully resolved settings dictionary, useful for templates - return {option.name: self.setting(option.name) for option in SETTINGS} + settings = {option.name: self.setting(option.name) for option in SETTINGS} + # Custom templates may still use the previous name of a setting + for old_name, name in SETTING_ALIASES.items(): + settings[old_name] = settings[name] + return settings def _metadata_recursive_update(self, orig, updated): if not isinstance(orig, dict) or not isinstance(updated, dict): diff --git a/datasette/cli.py b/datasette/cli.py index e83de93a33..bdd1cb3d9d 100644 --- a/datasette/cli.py +++ b/datasette/cli.py @@ -18,6 +18,7 @@ from .app import ( DEFAULT_SETTINGS, + SETTING_ALIASES, SETTINGS, SQLITE_LIMIT_ATTACHED, Datasette, @@ -72,6 +73,8 @@ class Setting(CompositeParamType): def convert(self, config, param, ctx): name, value = config + # A renamed setting can still be set using its previous name + name = SETTING_ALIASES.get(name, name) if name in DEFAULT_SETTINGS: # For backwards compatibility with how this worked prior to # Datasette 1.0, we turn bare setting names into setting.name diff --git a/datasette/templates/_export_dialog.html b/datasette/templates/_export_dialog.html index f528c120f8..54d39499a1 100644 --- a/datasette/templates/_export_dialog.html +++ b/datasette/templates/_export_dialog.html @@ -17,7 +17,7 @@ {% set export_later = export_rows.later if export_rows else false %} {#- "Include all rows" streams every row from the first one, so offer it on every later page, and on the first page when CSV would stop short -#} -{% 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_csv_stream %} +{% 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 %} {% macro rows_text(n) %}{{ "{:,}".format(n) }} row{{ "" if n == 1 else "s" }}{% endmacro %} {#- How many rows an export returns. JSON and plugin formats return the rows on this page; TSV and CSV ask for _size=max, starting from this page. @@ -101,7 +101,7 @@ {% if expandable_columns or csv_stream %}
{% if expandable_columns %}{% endif %} - {% if csv_stream %} Include all {{ rows_text(export_rows.total) if export_rows.total is not none else "rows" }}{% if export_later %} from the first page{% endif %}{% endif %} + {% if csv_stream %} Include all {{ rows_text(export_rows.total) if export_rows.total is not none else "rows" }}{% if export_later %} from the first page{% endif %}{% endif %}
{% endif %} {% for key, value in url_csv_hidden_args %} diff --git a/datasette/views/base.py b/datasette/views/base.py index 61426bc0d5..7b14fd84dc 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -213,7 +213,7 @@ def stream_requested(datasette, request, format_): return False if not datasette._renderer_can_stream.get(format_): return False - if not datasette.setting("allow_csv_stream"): + if not datasette.setting("allow_stream"): raise BadRequest("Streaming is disabled") if request.args.get("_next"): raise BadRequest("_next not allowed when streaming") @@ -234,7 +234,7 @@ async def _limit_stream_size(body, limit_mb): sent += len(chunk) if sent > limit_bytes: raise StreamSizeExceeded( - f"Response is larger than the {limit_mb}MB max_csv_mb limit" + f"Response is larger than the {limit_mb}MB max_stream_mb limit" ) yield chunk finally: @@ -315,7 +315,7 @@ async def render_with_output_renderer( ) # Streamed responses are limited in size - limit_mb = datasette.setting("max_csv_mb") + limit_mb = datasette.setting("max_stream_mb") if limit_mb and hasattr(response.body, "__aiter__"): response.body = _limit_stream_size(response.body, limit_mb) return response diff --git a/docs/changelog.rst b/docs/changelog.rst index 5a469f29b8..5d8d972485 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,7 +12,8 @@ Unreleased - 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`. - 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`) - 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`) -- **Breaking change**: an "include all rows" export that fails part of the way through, or that reaches the :ref:`setting_max_csv_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. +- **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. +- 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. - ``?_dl=1`` now adds a ``content-disposition: attachment`` header for every export format, not only CSV and TSV. - New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``. - ``csv`` and ``tsv`` are now included in the ``?_extra=renderers`` extra. diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index cfb2b5c55a..7d3e06ba2a 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -275,10 +275,10 @@ These can be passed to ``datasette serve`` using ``datasette serve --setting nam max-age= header) (default=5) cache_size_kb SQLite cache size in KB (0 == use SQLite default) (default=0) - allow_csv_stream Allow .csv?_stream=1 to download all rows - (ignoring max_returned_rows) (default=True) - max_csv_mb Maximum size allowed for CSV export in MB - set 0 - to disable this limit (default=100) + allow_stream Allow ?_stream=1 to export all rows (ignoring + max_returned_rows) (default=True) + max_stream_mb Maximum size allowed for a streamed export in MB + - set 0 to disable this limit (default=100) truncate_cells_html Truncate cells longer than this in HTML table view - set 0 to disable (default=2048) force_https_urls Force URLs in API output to always use https:// diff --git a/docs/csv_export.rst b/docs/csv_export.rst index 9d307a87d9..18b4149554 100644 --- a/docs/csv_export.rst +++ b/docs/csv_export.rst @@ -106,9 +106,9 @@ If a table returns more than 100MB of data Datasette stops and drops the connection, so the download fails instead of saving a file that is silently missing rows. The same thing happens if an error occurs part of the way through. -You can increase or remove this limit using the :ref:`setting_max_csv_mb` config +You can increase or remove this limit using the :ref:`setting_max_stream_mb` config setting. You can also disable the *include all rows* option entirely using -:ref:`setting_allow_csv_stream`. +:ref:`setting_allow_stream`. CSV and TSV are implemented as :ref:`output renderers ` that stream their rows. Plugins can add other formats that work the same way, see diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 95e44802e6..05c5a396a3 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -784,7 +784,7 @@ Datasette's own :ref:`CSV and TSV export ` is implemented this way. - ``?_stream=1`` is ignored by formats that do not accept ``row_stream``. - Only tables and views have more than one page. For a row, or the results of a SQL query, ``row_stream`` yields the same rows as ``rows``. - ``rows``, ``page`` and the other arguments describe the first page. Everything that could result in an error page - an invalid filter, a permission check - has already happened by the time your function is called. -- :ref:`setting_allow_csv_stream` and :ref:`setting_max_csv_mb` apply to every format, not only CSV. A streamed response that grows larger than ``max_csv_mb`` is cut off by dropping the connection, as described in :ref:`internals_response_stream`. +- :ref:`setting_allow_stream` and :ref:`setting_max_stream_mb` apply to every format, not only CSV. A streamed response that grows larger than ``max_stream_mb`` is cut off by dropping the connection, as described in :ref:`internals_response_stream`. Any format can be downloaded as a file by adding ``?_dl=1`` to the URL, which adds a ``content-disposition: attachment`` header with a filename ending in the format's extension. A response that sets its own ``content-disposition`` header is left alone. diff --git a/docs/settings.rst b/docs/settings.rst index 13e6f4b6f1..7f4d1b6680 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -406,13 +406,13 @@ Sets the amount of memory SQLite uses for its `per-connection cache Date: Sun, 15 Nov 2026 04:18:50 +0000 Subject: [PATCH 07/10] Remove unused LimitedWriter, EscapeHtmlWriter and WriteLimitExceeded These were only used by stream_csv(), which the CSV output renderer replaced. AsgiStream stays, since plugins use it. Refs #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/utils/__init__.py | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/datasette/utils/__init__.py b/datasette/utils/__init__.py index b8e06fce25..dee255504f 100644 --- a/datasette/utils/__init__.py +++ b/datasette/utils/__init__.py @@ -1114,31 +1114,6 @@ class ValueAsBooleanError(ValueError): pass -class WriteLimitExceeded(Exception): - pass - - -class LimitedWriter: - def __init__(self, writer, limit_mb): - self.writer = writer - self.limit_bytes = limit_mb * 1024 * 1024 - self.bytes_count = 0 - - async def write(self, bytes): - self.bytes_count += len(bytes) - if self.limit_bytes and (self.bytes_count > self.limit_bytes): - raise WriteLimitExceeded(f"CSV contains more than {self.limit_bytes} bytes") - await self.writer.write(bytes) - - -class EscapeHtmlWriter: - def __init__(self, writer): - self.writer = writer - - async def write(self, content): - await self.writer.write(markupsafe.escape(content)) - - _infinities = {float("inf"), float("-inf")} From 0c9a34882f2b460cc1912c3ef4c84e9fb7e154da Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:32:54 +0000 Subject: [PATCH 08/10] view_name is now "query" for SQL query pages Plugin hooks were told a query page was "database" - the same as the page listing a database's tables - except for output renderer render() functions, which were told "table" while can_render() for the same format was told "database". Arbitrary SQL and stored query pages now pass view_name="query" to template hooks, render() and can_render() alike. Refs #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/views/database.py | 6 ++-- datasette/views/table_extras.py | 2 +- docs/changelog.rst | 1 + docs/plugin_hooks.rst | 4 +-- docs/upgrade_guide.md | 14 ++++++++ tests/test_plugins.py | 64 +++++++++++++++++++++++++++++++-- 6 files changed, 83 insertions(+), 8 deletions(-) diff --git a/datasette/views/database.py b/datasette/views/database.py index bd0c4a8b49..b4198105d3 100644 --- a/datasette/views/database.py +++ b/datasette/views/database.py @@ -934,7 +934,7 @@ async def query_metadata(): query_name=stored_query.name if stored_query else None, database=database, table=None, - view_name="table", + view_name="query", truncated=results.truncated if results else False, error=query_error, ) @@ -988,7 +988,7 @@ async def query_metadata(): request=request, path=path_without_format(request), full_path=path_without_format(request, include_query_string=True), - view_name="database", + view_name="query", ) it_can_render = await await_me_maybe(it_can_render) if it_can_render: @@ -1194,7 +1194,7 @@ async def query_actions(): query_actions=query_actions, ), request=request, - view_name="database", + view_name="query", ), headers=headers, ) diff --git a/datasette/views/table_extras.py b/datasette/views/table_extras.py index d2e1f66394..b182e9655f 100644 --- a/datasette/views/table_extras.py +++ b/datasette/views/table_extras.py @@ -1123,7 +1123,7 @@ async def resolve(self, context, expandable_columns, query): if expandable_columns: url_labels_extra = {"_labels": "on"} table_name = context.table_name - view_name = "table" if context.scope == ExtraScope.TABLE else "database" + view_name = context.scope.value # "table", "row" or "query" for key, (_, can_render) in context.datasette.renderers.items(): it_can_render = call_with_supported_arguments( can_render, diff --git a/docs/changelog.rst b/docs/changelog.rst index 869aaf4cbe..fc3060494c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,7 @@ Unreleased - 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`) - **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. - 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. +- **Breaking change**: the ``view_name`` passed to plugin hooks for SQL query pages, both arbitrary SQL and stored queries, is now ``"query"``. Template hooks such as :ref:`plugin_hook_extra_template_vars` were previously passed ``"database"`` for those pages. Output renderers were passed ``"table"`` by ``render`` and ``"database"`` by ``can_render``. See :ref:`the upgrade guide `. - ``?_dl=1`` now adds a ``content-disposition: attachment`` header for every export format, not only CSV and TSV. - New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``. - ``csv`` and ``tsv`` are now included in the ``?_extra=renderers`` extra. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 7e7686ab11..17452197f9 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -209,7 +209,7 @@ Extra template variables that should be made available in the rendered template The names of the database columns that will be displayed on this page. ``None`` if the page does not contain a table. ``view_name`` - string - The name of the view being displayed. (``index``, ``database``, ``table``, and ``row`` are the most important ones.) + The name of the view being displayed. (``index``, ``database``, ``table``, ``row`` and ``query`` are the most important ones.) ``query`` is used for both arbitrary SQL queries and stored queries. ``request`` - :ref:`internals_request` or None The current HTTP request. This can be ``None`` if the request object is not available. @@ -695,7 +695,7 @@ When a request is received, the ``"render"`` callback function is called with ze If the query response was truncated - for example a SQL query returning more than 1,000 results where pagination is not available - this will be ``True``. ``view_name`` - string - The name of the current view being called. ``index``, ``database``, ``table``, and ``row`` are the most important ones. + The name of the current view being called: ``table``, ``row`` or ``query``. ``query`` is used for both arbitrary SQL queries and stored queries. ``can_render`` is passed the same value. ``page`` - dictionary Everything the JSON version of this page returns alongside its rows: the :ref:`extras ` this format declared using its ``"extras"`` key, any that were requested using ``?_extra=`` in the URL, and the keys that type of page always includes. For table pages those are ``next``, the token for the next page of results, and ``next_url``, the URL of that page in this format - both are ``None`` on the last page. Extras that are not available for the current page are omitted. diff --git a/docs/upgrade_guide.md b/docs/upgrade_guide.md index 33a8343ba4..c7f67180a7 100644 --- a/docs/upgrade_guide.md +++ b/docs/upgrade_guide.md @@ -29,6 +29,20 @@ The URL for executing a SQL query now looks like this: **This isn't a breaking change.** API calls to the older ``/databasename?sql=...`` endpoint will redirect to the new ``databasename/-/query?sql=...`` endpoint. Upgrading to the new URL is recommended to avoid the overhead of the additional redirect. +(upgrade_guide_v1_view_name_query)= +### `view_name` is now `"query"` for SQL query pages + +Plugin hooks that accept a `view_name` argument - `extra_template_vars()`, `extra_css_urls()`, `extra_js_urls()`, `extra_body_script()` and the `render` and `can_render` functions of `register_output_renderer()` - are now passed `"query"` for pages that show the results of a SQL query. This applies to arbitrary SQL at `/databasename/-/query?sql=...` and to stored queries. + +Previously those pages used `"database"`, the same value as the page listing the tables in a database, except for the output renderer `render` function which was passed `"table"`. + +If your plugin checks `view_name == "database"` and should still run on query pages, update it to check for both: + +```python +if view_name in ("database", "query"): + ... +``` + (upgrade_guide_v1_metadata)= ### Metadata changes diff --git a/tests/test_plugins.py b/tests/test_plugins.py index 3eff701847..8f94533a79 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -567,7 +567,14 @@ def extra_template_vars(view_name): conn.executescript(TABLES) conn.close() return _TestClient( - Datasette([db_path], template_dir=str(templates), plugins_dir=str(plugins)) + Datasette( + [db_path], + template_dir=str(templates), + plugins_dir=str(plugins), + config={ + "databases": {"fixtures": {"queries": {"stored_query": "select 1"}}} + }, + ) ) @@ -579,7 +586,8 @@ def extra_template_vars(view_name): ("/fixtures/facetable", "table"), ("/fixtures/facetable/1", "row"), ("/-/versions", "json_data"), - ("/fixtures/-/query?sql=select+1", "database"), + ("/fixtures/-/query?sql=select+1", "query"), + ("/fixtures/stored_query", "query"), ), ) def test_view_names(view_names_client, path, view_name): @@ -588,6 +596,58 @@ def test_view_names(view_names_client, path, view_name): assert f"view_name:{view_name}" == response.text +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path,html_path,expected_view_name,expected_query_name", + ( + ("/fixtures/facetable.testall", "/fixtures/facetable", "table", None), + ( + "/fixtures/simple_primary_key/1.testall", + "/fixtures/simple_primary_key/1", + "row", + None, + ), + # Arbitrary SQL + ( + "/fixtures/-/query.testall?sql=select+1+as+one", + "/fixtures/-/query?sql=select+1+as+one", + "query", + None, + ), + # Stored query + ( + "/fixtures/neighborhood_search.testall?text=town", + "/fixtures/neighborhood_search?text=town", + "query", + "neighborhood_search", + ), + ), +) +async def test_hook_register_output_renderer_view_name( + ds_client, path, html_path, expected_view_name, expected_query_name +): + # render() is told which kind of page it is rendering + response = await ds_client.get(path) + assert response.status_code == 200 + data = response.json() + assert data["view_name"] == expected_view_name + assert data["query_name"] == expected_query_name + # can_render() is passed the same view_name, when the HTML page + # checks which formats to offer in its export dialog + ds_client.ds._can_render_saw = None + response = await ds_client.get(html_path) + assert response.status_code == 200 + assert ds_client.ds._can_render_saw["view_name"] == expected_view_name + + +@pytest.mark.asyncio +async def test_hook_register_output_renderer_view_name_for_renderers_extra(ds_client): + ds_client.ds._can_render_saw = None + response = await ds_client.get("/fixtures/facetable.json?_extra=renderers") + assert response.status_code == 200 + assert ds_client.ds._can_render_saw["view_name"] == "table" + + @pytest.mark.asyncio async def test_hook_register_output_renderer_no_parameters(ds_client): response = await ds_client.get("/fixtures/facetable.testnone") From baba185b40623b3d10e4d1ec4ce03b18c7927982 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:41:48 +0000 Subject: [PATCH 09/10] Deprecation warning for render functions that accept data= or args= An output renderer whose render function accepts the undocumented data or args arguments now triggers a DeprecationWarning when it is registered. The warning is reported against the render function's own file and line. Both arguments are still passed. Use the page argument in place of data, and request.args in place of args. Refs #2770, #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 44 ++++++++++- docs/changelog.rst | 1 + tests/plugins/register_output_renderer.py | 1 - tests/test_renderer_extras.py | 91 +++++++++++++++++++++++ 4 files changed, 132 insertions(+), 5 deletions(-) diff --git a/datasette/app.py b/datasette/app.py index 6ddb3ab4a1..1277efb596 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -24,6 +24,7 @@ import time import types import urllib.parse +import warnings from concurrent import futures from pathlib import Path @@ -314,6 +315,37 @@ class PermissionCheck: } +# Arguments that output renderer render functions should no longer accept, +# mapped to what to use instead +DEPRECATED_RENDER_ARGUMENTS = { + "data": "Declare the extras it needs and use the page argument instead", + "args": "Use request.args instead", +} + + +def _warn_deprecated_render_argument(render, extension, argument, replacement): + message = ( + f"Output renderer '{extension}' accepts the {argument} argument, which is " + f"deprecated and will be removed before Datasette 1.0. {replacement}: " + "https://docs.datasette.io/en/latest/plugin_hooks.html" + "#register-output-renderer-datasette" + ) + code = getattr(render, "__code__", None) + if code is None: + warnings.warn(message, DeprecationWarning, stacklevel=2) + else: + # Report the warning against the render function itself, so the + # plugin author can see which code needs to change + warnings.warn_explicit( + message, + DeprecationWarning, + filename=code.co_filename, + lineno=code.co_firstlineno, + # module must be a string or some warnings are silently dropped + module=getattr(render, "__module__", None) or "datasette", + ) + + def resolve_setting_aliases(settings, source): """ Return a copy of the settings dictionary with any old setting names @@ -2612,11 +2644,15 @@ def _register_renderers(self): f"Output renderer '{extension}' extras must be a list of strings" ) self._renderer_extras[extension] = list(declared_extras) + render = self.renderers[extension][0] + render_parameters = inspect.signature(render).parameters # Renderers that accept row_stream can stream every row - self._renderer_can_stream[extension] = ( - "row_stream" - in inspect.signature(self.renderers[extension][0]).parameters - ) + self._renderer_can_stream[extension] = "row_stream" in render_parameters + for deprecated, replacement in DEPRECATED_RENDER_ARGUMENTS.items(): + if deprecated in render_parameters: + _warn_deprecated_render_argument( + render, extension, deprecated, replacement + ) # How the export dialog presents this format is_binary = bool(renderer.get("is_binary")) is_webpage = bool(renderer.get("is_webpage")) diff --git a/docs/changelog.rst b/docs/changelog.rst index fc3060494c..a63f1769fe 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,7 @@ Unreleased - **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. - 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. - **Breaking change**: the ``view_name`` passed to plugin hooks for SQL query pages, both arbitrary SQL and stored queries, is now ``"query"``. Template hooks such as :ref:`plugin_hook_extra_template_vars` were previously passed ``"database"`` for those pages. Output renderers were passed ``"table"`` by ``render`` and ``"database"`` by ``can_render``. See :ref:`the upgrade guide `. +- Output renderers whose ``render`` function accepts the undocumented ``data`` or ``args`` arguments now trigger a ``DeprecationWarning`` when Datasette starts. Those arguments will be removed before Datasette 1.0. Use the ``page`` argument in place of ``data``, and ``request.args`` in place of ``args``. (:issue:`2770`) - ``?_dl=1`` now adds a ``content-disposition: attachment`` header for every export format, not only CSV and TSV. - New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``. - ``csv`` and ``tsv`` are now included in the ``?_extra=renderers`` extra. diff --git a/tests/plugins/register_output_renderer.py b/tests/plugins/register_output_renderer.py index 68fe118680..ab91b25612 100644 --- a/tests/plugins/register_output_renderer.py +++ b/tests/plugins/register_output_renderer.py @@ -46,7 +46,6 @@ async def render_test_all_parameters( path, full_path, view_name, - data, ): headers = {} for custom_header in request.args.getlist("header"): diff --git a/tests/test_renderer_extras.py b/tests/test_renderer_extras.py index 31bf392dc4..28520c3cb7 100644 --- a/tests/test_renderer_extras.py +++ b/tests/test_renderer_extras.py @@ -198,3 +198,94 @@ def test_json_renderer_uses_documented_arguments_only(ds): parameters = set(inspect.signature(render).parameters) assert not parameters & {"data", "args"} assert {"rows", "columns", "page"} <= parameters + + +def _render_with_data(data, rows): + return Response.text("ok") + + +def _render_with_args(args, rows): + return Response.text("ok") + + +@pytest.mark.parametrize( + "render,argument,replacement", + ( + ( + _render_with_data, + "data", + "Declare the extras it needs and use the page argument instead", + ), + (_render_with_args, "args", "Use request.args instead"), + ), +) +def test_render_function_accepting_data_or_args_is_deprecated( + render, argument, replacement +): + class DeprecatedPlugin: + __name__ = "DeprecatedPlugin" + + @hookimpl + def register_output_renderer(self): + return {"extension": "deprecated", "render": render} + + pm.register(DeprecatedPlugin(), name="deprecated_renderer") + try: + with pytest.warns(DeprecationWarning) as record: + ds = Datasette(memory=True) + ds.close() + finally: + pm.unregister(name="deprecated_renderer") + messages = [ + str(warning.message) + for warning in record + if "Output renderer 'deprecated'" in str(warning.message) + ] + assert len(messages) == 1 + assert messages[0].startswith( + f"Output renderer 'deprecated' accepts the {argument} argument, which is " + f"deprecated and will be removed before Datasette 1.0. {replacement}: " + ) + + +@pytest.mark.asyncio +async def test_deprecated_data_and_args_are_still_passed(): + def render(data, args): + return Response.json({"ok": data["ok"], "one": args["one"]}) + + class DeprecatedPlugin: + __name__ = "DeprecatedPlugin" + + @hookimpl + def register_output_renderer(self): + return {"extension": "deprecated", "render": render} + + pm.register(DeprecatedPlugin(), name="deprecated_renderer") + try: + with pytest.warns(DeprecationWarning) as record: + ds = Datasette(memory=True) + # The warning points at the render function, not at Datasette + ours = [w for w in record if "Output renderer 'deprecated'" in str(w.message)] + assert len(ours) == 2 + assert {w.filename for w in ours} == {__file__} + assert {w.lineno for w in ours} == {render.__code__.co_firstlineno} + response = await ds.client.get("/_memory/-/query.deprecated?sql=select+1&one=1") + assert response.json() == {"ok": True, "one": "1"} + ds.close() + finally: + pm.unregister(name="deprecated_renderer") + + +def test_no_deprecation_warning_for_other_renderers(ds): + import warnings + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + other = Datasette(memory=True) + other.close() + # The ds fixture registers renderers that only use page - and the + # default CSV, TSV, blob and JSON renderers must not warn either + extensions = ("declared", "nonedeclared", "noargument", "csv", "tsv", "json") + for warning in record: + for extension in extensions: + assert f"Output renderer '{extension}'" not in str(warning.message) From f928f3c94c9b21b2cbd316632732bc552c2860f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:53:00 +0000 Subject: [PATCH 10/10] Output renderers must return a Response, remove dict returns and callback A render function that returns a dictionary of body, content_type, status_code and headers - deprecated since Datasette 0.49 - is now an error naming the format and saying to return a Response. Any other return type gets the same error, replacing an assert. The "callback" key, the pre-0.49 name for "render", is no longer accepted. Registering a renderer without a render function is a startup error, which mentions the rename if "callback" was used. Closes #954, refs #2936 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J --- datasette/app.py | 12 ++++- datasette/views/base.py | 16 +++--- docs/changelog.rst | 1 + docs/plugin_hooks.rst | 16 +----- docs/upgrade_guide.md | 34 +++++++++++++ tests/plugins/messages_output_renderer.py | 4 +- tests/plugins/register_output_renderer.py | 19 +++++--- tests/test_csv.py | 3 +- tests/test_plugins.py | 59 ++++++++++++++++++++++- 9 files changed, 125 insertions(+), 39 deletions(-) diff --git a/datasette/app.py b/datasette/app.py index 1277efb596..3453d74610 100644 --- a/datasette/app.py +++ b/datasette/app.py @@ -2630,9 +2630,17 @@ def _register_renderers(self): for renderer in hook_renderers: extension = renderer["extension"] + if not renderer.get("render"): + raise StartupError( + f"Output renderer '{extension}' must have a 'render' function" + + ( + " - the 'callback' key has been renamed to 'render'" + if "callback" in renderer + else "" + ) + ) self.renderers[extension] = ( - # It used to be called "callback" - remove this in Datasette 1.0 - renderer.get("render") or renderer["callback"], + renderer["render"], renderer.get("can_render") or (lambda: True), ) # Extras to resolve and pass to the render function as extras= diff --git a/datasette/views/base.py b/datasette/views/base.py index 2b41629e39..5cc50bbc1e 100644 --- a/datasette/views/base.py +++ b/datasette/views/base.py @@ -294,17 +294,13 @@ async def render_with_output_renderer( result = await result if result is None: raise NotFound("No data") - if isinstance(result, dict): - response = Response( - body=result.get("body"), - status=result.get("status_code") or 200, - content_type=result.get("content_type", "text/plain"), - headers=result.get("headers"), + if not isinstance(result, Response): + raise TypeError( + f"Output renderer '{format_}' returned {type(result).__name__}: " + "render functions must return a datasette.Response object, " + "or None if they cannot render the data" ) - elif isinstance(result, Response): - response = result - else: - assert False, f"{result} should be dict or Response" + response = result # ?_dl=1 downloads the response as a file if ( diff --git a/docs/changelog.rst b/docs/changelog.rst index a63f1769fe..26be29758e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,7 @@ Unreleased - **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. - 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. - **Breaking change**: the ``view_name`` passed to plugin hooks for SQL query pages, both arbitrary SQL and stored queries, is now ``"query"``. Template hooks such as :ref:`plugin_hook_extra_template_vars` were previously passed ``"database"`` for those pages. Output renderers were passed ``"table"`` by ``render`` and ``"database"`` by ``can_render``. See :ref:`the upgrade guide `. +- **Breaking change**: output renderer ``render`` functions must now return a :ref:`Response ` object, or ``None``. Returning a dictionary with ``body``, ``content_type``, ``status_code`` and ``headers`` keys, deprecated since Datasette 0.49, is now an error. The ``"callback"`` key, the pre-0.49 name for ``"render"``, has also been removed. See :ref:`the upgrade guide `. (:issue:`954`) - Output renderers whose ``render`` function accepts the undocumented ``data`` or ``args`` arguments now trigger a ``DeprecationWarning`` when Datasette starts. Those arguments will be removed before Datasette 1.0. Use the ``page`` argument in place of ``data``, and ``request.args`` in place of ``args``. (:issue:`2770`) - ``?_dl=1`` now adds a ``content-disposition: attachment`` header for every export format, not only CSV and TSV. - New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``. diff --git a/docs/plugin_hooks.rst b/docs/plugin_hooks.rst index 17452197f9..2fd5211b99 100644 --- a/docs/plugin_hooks.rst +++ b/docs/plugin_hooks.rst @@ -700,21 +700,7 @@ When a request is received, the ``"render"`` callback function is called with ze ``page`` - dictionary Everything the JSON version of this page returns alongside its rows: the :ref:`extras ` this format declared using its ``"extras"`` key, any that were requested using ``?_extra=`` in the URL, and the keys that type of page always includes. For table pages those are ``next``, the token for the next page of results, and ``next_url``, the URL of that page in this format - both are ``None`` on the last page. Extras that are not available for the current page are omitted. -The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller. - -It can also return a dictionary with the following keys. This format is **deprecated** as-of Datasette 0.49 and will be removed by Datasette 1.0. - -``body`` - string or bytes, optional - The response body, default empty - -``content_type`` - string, optional - The Content-Type header, default ``text/plain`` - -``status_code`` - integer, optional - The HTTP status code, default 200 - -``headers`` - dictionary, optional - Extra HTTP headers to be returned in the response. +The callback function can return ``None``, if it is unable to render the data, or a :ref:`internals_response` that will be returned to the caller. Returning anything else is an error. An example of an output renderer callback function: diff --git a/docs/upgrade_guide.md b/docs/upgrade_guide.md index c7f67180a7..b2630a3e9f 100644 --- a/docs/upgrade_guide.md +++ b/docs/upgrade_guide.md @@ -43,6 +43,40 @@ if view_name in ("database", "query"): ... ``` +(upgrade_guide_v1_renderer_response)= +### Output renderers must return a `Response` + +The `render` function of an output renderer registered using `register_output_renderer()` must now return a `Response` object, or `None` if it cannot render the data. Returning a dictionary, which was deprecated in Datasette 0.49, is now an error. + +Change this: + +```python +def render_demo(): + return { + "body": "Hello", + "content_type": "text/plain", + "status_code": 200, + "headers": {"x-demo": "1"}, + } +``` + +To this: + +```python +from datasette import Response + + +def render_demo(): + return Response( + "Hello", + content_type="text/plain", + status=200, + headers={"x-demo": "1"}, + ) +``` + +The dictionary returned by `register_output_renderer()` itself must use the `"render"` key for that function. The older `"callback"` key is no longer accepted. + (upgrade_guide_v1_metadata)= ### Metadata changes diff --git a/tests/plugins/messages_output_renderer.py b/tests/plugins/messages_output_renderer.py index 6b52f8011e..fd666fe414 100644 --- a/tests/plugins/messages_output_renderer.py +++ b/tests/plugins/messages_output_renderer.py @@ -1,4 +1,4 @@ -from datasette import hookimpl +from datasette import Response, hookimpl def render_message_debug(datasette, request): @@ -7,7 +7,7 @@ def render_message_debug(datasette, request): datasette.add_message( request, request.args["add_msg"], getattr(datasette, msg_type) ) - return {"body": "Hello from message debug"} + return Response.text("Hello from message debug") @hookimpl diff --git a/tests/plugins/register_output_renderer.py b/tests/plugins/register_output_renderer.py index ab91b25612..6aa1a78301 100644 --- a/tests/plugins/register_output_renderer.py +++ b/tests/plugins/register_output_renderer.py @@ -52,8 +52,8 @@ async def render_test_all_parameters( key, value = custom_header.split(":") headers[key] = value result = await datasette.databases["fixtures"].execute("select 1 + 1") - return { - "body": json.dumps( + return Response( + json.dumps( { "datasette": datasette, "columns": columns, @@ -70,19 +70,22 @@ async def render_test_all_parameters( }, default=repr, ), - "content_type": request.args.get("content_type", "text/plain"), - "status_code": int(request.args.get("status_code", 200)), - "headers": headers, - } + content_type=request.args.get("content_type", "text/plain"), + status=int(request.args.get("status_code", 200)), + headers=headers, + ) def render_test_no_parameters(): - return {"body": "Hello"} + return Response.text("Hello") async def render_response(request): if request.args.get("_broken"): return "this should break" + if request.args.get("_dict"): + # The pre-1.0 way of returning a response + return {"body": "Hello", "content_type": "text/plain"} return Response.json({"this_is": "json"}) @@ -94,6 +97,6 @@ def register_output_renderer(datasette): "render": render_test_all_parameters, "can_render": can_render, }, - {"extension": "testnone", "callback": render_test_no_parameters}, + {"extension": "testnone", "render": render_test_no_parameters}, {"extension": "testresponse", "render": render_response}, ] diff --git a/tests/test_csv.py b/tests/test_csv.py index e8caefe8e1..b645d7dd46 100644 --- a/tests/test_csv.py +++ b/tests/test_csv.py @@ -4,6 +4,7 @@ from bs4 import BeautifulSoup as Soup from datasette.app import Datasette +from datasette.utils.asgi import Response EXPECTED_TABLE_CSV = """id,content 1,hello @@ -394,7 +395,7 @@ class TsvPlugin: def register_output_renderer(self): return { "extension": "tsv", - "render": lambda: {"body": "from the plugin"}, + "render": lambda: Response.text("from the plugin"), } plugin = TsvPlugin() diff --git a/tests/test_plugins.py b/tests/test_plugins.py index 8f94533a79..c1f4a617df 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -779,7 +779,64 @@ async def test_hook_register_output_renderer_returning_response(ds_client): async def test_hook_register_output_renderer_returning_broken_value(ds_client): response = await ds_client.get("/fixtures/facetable.testresponse?_broken=1") assert response.status_code == 500 - assert "this should break should be dict or Response" in response.text + assert ( + "Output renderer 'testresponse' returned str: render functions " + "must return a datasette.Response object, or None if they cannot " + "render the data" + ) in response.text + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "path", + ( + "/fixtures/facetable.testresponse?_dict=1", + "/fixtures/simple_primary_key/1.testresponse?_dict=1", + "/fixtures/-/query.testresponse?sql=select+1&_dict=1", + ), +) +async def test_hook_register_output_renderer_returning_dict_is_an_error( + ds_client, path +): + # Returning a dictionary was deprecated in Datasette 0.49 and has + # since been removed + response = await ds_client.get(path) + assert response.status_code == 500 + assert "Output renderer 'testresponse' returned dict" in response.text + assert "must return a datasette.Response object" in response.text + + +@pytest.mark.parametrize( + "renderer,expected", + ( + ( + {"extension": "old", "callback": lambda: Response.text("x")}, + ( + "Output renderer 'old' must have a 'render' function - " + "the 'callback' key has been renamed to 'render'" + ), + ), + ( + {"extension": "old"}, + "Output renderer 'old' must have a 'render' function", + ), + ), +) +def test_hook_register_output_renderer_requires_render(renderer, expected): + class Plugin: + __name__ = "Plugin" + + @hookimpl + def register_output_renderer(self): + return renderer + + pm.register(Plugin(), name="renderer_without_render") + try: + with pytest.raises(StartupError) as ex: + Datasette(memory=True) + assert str(ex.value) == expected + finally: + pm.unregister(name="renderer_without_render") @pytest.mark.asyncio