Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: better formats for table and charts. avoid additional round trip (#4670)

Myles Scolnick900ac4ef6180
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 39067feef6..42635ec302 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1268,32 +1268,6 @@ export const UserConfigForm: React.FC = () => {
notebook to take effect.
</p>
- <FormField
- control={form.control}
- name="experimental.secrets"
- render={({ field }) => (
- <div className="flex flex-col gap-y-1">
- <FormItem className={formItemClasses}>
- <FormLabel className="font-normal">
- Secrets Management
- </FormLabel>
- <FormControl>
- <Checkbox
- data-testid="secrets-checkbox"
- checked={field.value === true}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- <FormDescription>
- Enable secrets management. This allows you to manage secrets
- in your notebooks. Currently only reading{" "}
- <Kbd className="inline">.env</Kbd> files are supported.
- </FormDescription>
- </div>
- )}
- />
-
{!isWasm() && (
<FormField
control={form.control}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 6570db3edb..b19888c734 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -52,6 +52,7 @@ import {
} from "@/components/data-table/filters";
import { isStaticNotebook } from "@/core/static/static-state";
import { vegaLoadData } from "./vega/loader";
+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
type CsvURL = string;
type TableData<T> = T[] | CsvURL;
@@ -429,6 +430,15 @@ export const LoadingDataTableComponent = memo(
};
}
+ // If it looks like json, parse it
+ if (tableData.startsWith("{") || tableData.startsWith("[")) {
+ return {
+ rows: jsonParseWithSpecialChar(tableData),
+ totalRows: totalRows,
+ cellStyles,
+ };
+ }
+
// Otherwise, load the data from the URL
tableData = await vegaLoadData(
tableData,
diff --git a/frontend/src/plugins/impl/vega/batched.ts b/frontend/src/plugins/impl/vega/batched.ts
index 6b88924f25..c5381c18c4 100644
--- a/frontend/src/plugins/impl/vega/batched.ts
+++ b/frontend/src/plugins/impl/vega/batched.ts
@@ -2,9 +2,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { batch } from "@/utils/batch-requests";
import { createLoader, type Loader } from "./vega-loader";
+import { tableFromIPC } from "@uwdata/flechette";
export function createBatchedLoader(): Loader {
- const loader = createLoader();
+ const loader = withArrowSupport(createLoader());
const toKey = (request: unknown) => JSON.stringify(request);
return {
load: batch(loader.load.bind(loader) as any, toKey),
@@ -13,3 +14,27 @@ export function createBatchedLoader(): Loader {
file: batch(loader.file.bind(loader), toKey),
};
}
+
+export function withArrowSupport(loader: Loader): Loader {
+ return {
+ ...loader,
+ async load(uri: string, options?: unknown) {
+ if (uri.endsWith(".arrow")) {
+ const arrow = await batchedArrowLoader(uri);
+ return tableFromIPC(arrow, {
+ // useProxy=true makes aggregations like year(data) fail
+ useProxy: false,
+ }).toArray();
+ }
+ return loader.load(uri, options);
+ },
+ };
+}
+
+/**
+ * Batch requests to the same URL returning the same promise for all calls with the same key.
+ */
+export const batchedArrowLoader = batch(
+ (url: string) => fetch(url).then((r) => r.arrayBuffer()),
+ (url: string) => url,
+);
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index b12773b1a2..5c79372e8f 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -5,8 +5,7 @@ import { typeParsers, read, type DataType } from "./vega-loader";
import { Objects } from "@/utils/objects";
import { Logger } from "@/utils/Logger";
import { tableFromIPC } from "@uwdata/flechette";
-import { batch } from "@/utils/batch-requests";
-import { createBatchedLoader } from "./batched";
+import { batchedArrowLoader, createBatchedLoader } from "./batched";
type Unsubscribe = () => void;
type Middleware = () => Unsubscribe;
@@ -126,14 +125,6 @@ typeParsers.boolean = customBooleanParser;
export const vegaLoader = createBatchedLoader();
-/**
- * Batch requests to the same URL returning the same promise for all calls with the same key.
- */
-export const batchedArrowLoader = batch(
- (url: string) => fetch(url).then((r) => r.arrayBuffer()),
- (url: string) => url,
-);
-
/**
* Load data from a URL and parse it according to the given format.
*
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 42bf32167c..373f0347a1 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -256,7 +256,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
)
# Save the manager to be used for selection
- data = result.take(args.page_size, offset).to_data()
+ data = result.take(args.page_size, offset).to_json_str()
return SearchTableResponse(
data=data,
total_rows=result.get_num_rows(force=True) or 0,
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index f4d8690622..5e2d24412f 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -112,7 +112,7 @@ CellStyles = dict[RowId, dict[ColumnName, dict[str, Any]]]
@dataclass(frozen=True)
class SearchTableResponse:
- data: Union[JSONType, str]
+ data: str
total_rows: Union[int, Literal["too_many"]]
cell_styles: Optional[CellStyles] = None
@@ -530,7 +530,7 @@ class table(
)
self._has_any_selection = True
- # We will need this when calling table manager's to_data()
+ # We will need this when calling table manager's to_json_str()
self._format_mapping = format_mapping
if pagination is False and total_rows != "too_many":
@@ -812,7 +812,7 @@ class table(
self._show_column_summaries != "stats"
and total_rows <= self._column_charts_row_limit
):
- chart_data = self._searched_manager.to_data({})
+ chart_data, _ = self._to_chart_data_url(self._searched_manager)
return ColumnSummaries(
data=chart_data,
@@ -820,6 +820,30 @@ class table(
is_disabled=False,
)
+ @classmethod
+ def _to_chart_data_url(
+ cls, table_manager: TableManager[Any]
+ ) -> tuple[str, Literal["csv", "json", "arrow"]]:
+ """
+ Get the data for the column summaries.
+
+ Arrow is preferred (less memory and faster)
+ fallback to CSV (more compact than JSON)
+
+ We return a URL instead of the data directly
+ so the browser can cache requests
+ """
+ try:
+ data_url = mo_data.arrow(table_manager.to_arrow_ipc()).url
+ return data_url, "arrow"
+ except NotImplementedError:
+ try:
+ data_url = mo_data.csv(table_manager.to_csv({})).url
+ return data_url, "csv"
+ except ValueError:
+ data_url = mo_data.json(table_manager.to_json({})).url
+ return data_url, "json"
+
def _get_data_url(self, args: EmptyArgs) -> GetDataUrlResponse:
"""Get the data URL for the entire table. Used for charting."""
del args
@@ -831,8 +855,10 @@ class table(
format=result["format"]["type"],
)
+ url, data_format = self._to_chart_data_url(self._searched_manager)
return GetDataUrlResponse(
- data_url=self._searched_manager.to_data({}), format="json"
+ data_url=url,
+ format=data_format,
)
@functools.lru_cache(maxsize=1) # noqa: B019
@@ -935,7 +961,7 @@ class table(
"""
offset = args.page_number * args.page_size
- def clamp_rows_and_columns(manager: TableManager[Any]) -> JSONType:
+ def clamp_rows_and_columns(manager: TableManager[Any]) -> str:
# Limit to page and column clamping for the frontend
data = manager.take(args.page_size, offset)
column_names = data.get_column_names()
@@ -944,7 +970,7 @@ class table(
and len(column_names) > self._max_columns
):
data = data.select_columns(column_names[: self._max_columns])
- return data.to_data(self._format_mapping)
+ return data.to_json_str(self._format_mapping)
# If no query or sort, return nothing
# The frontend will just show the original data
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 737929dcad..7478b971e0 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import functools
+import json
from collections import defaultdict
from collections.abc import Sequence
from typing import Any, Optional, Union, cast
@@ -9,6 +10,7 @@ from typing import Any, Optional, Union, cast
from marimo._data.models import ColumnSummary, ExternalDataType
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
+from marimo._plugins.core.json_encoder import WebComponentEncoder
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
@@ -85,11 +87,6 @@ class DefaultTableManager(TableManager[JsonTableData]):
def supports_filters(self) -> bool:
return False
- def to_data(
- self, format_mapping: Optional[FormatMapping] = None
- ) -> JSONType:
- return self._normalize_data(self.apply_formatting(format_mapping).data)
-
def to_csv_str(
self, format_mapping: Optional[FormatMapping] = None
) -> str:
@@ -103,11 +100,10 @@ class DefaultTableManager(TableManager[JsonTableData]):
def to_json_str(
self, format_mapping: Optional[FormatMapping] = None
) -> str:
- if isinstance(self.data, dict) and not self.is_column_oriented:
- return DefaultTableManager(
- self._normalize_data(self.data)
- ).to_json_str(format_mapping)
- return self._as_table_manager().to_json_str(format_mapping)
+ return json.dumps(
+ self._normalize_data(self.apply_formatting(format_mapping).data),
+ cls=WebComponentEncoder,
+ )
def to_parquet(self) -> bytes:
if isinstance(self.data, dict) and not self.is_column_oriented:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 8e5041f59a..2fb91f96d9 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -284,9 +284,18 @@ class NarwhalsTableManager(
def get_summary(self, column: str) -> ColumnSummary:
summary = self._get_summary_internal(column)
- for key, value in summary.__dict__.items():
- if value is not None:
- summary.__dict__[key] = unwrap_py_scalar(value)
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message="Discarding nonzero nanoseconds in conversion",
+ category=UserWarning,
+ )
+
+ for key, value in summary.__dict__.items():
+ if value is not None:
+ summary.__dict__[key] = unwrap_py_scalar(value)
return summary
def _get_summary_internal(self, column: str) -> ColumnSummary:
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 92e6b3603f..fe00fe4955 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -5,9 +5,7 @@ import abc
from dataclasses import dataclass
from typing import Any, Generic, NamedTuple, Optional, TypeVar, Union
-import marimo._output.data.data as mo_data
from marimo._data.models import ColumnSummary, DataType, ExternalDataType
-from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._impl.tables.format import FormatMapping
T = TypeVar("T")
@@ -56,18 +54,6 @@ class TableManager(abc.ABC, Generic[T]):
def __init__(self, data: T) -> None:
self.data = data
- def to_data(
- self,
- format_mapping: Optional[FormatMapping] = None,
- ) -> JSONType:
- """
- The best way to represent the data in a table as JSON.
-
- By default, this method calls `to_json` and returns the result as
- a string. `to_json` supports most data types (e.g. nested lists)
- """
- return mo_data.json(self.to_json(format_mapping)).url
-
def supports_download(self) -> bool:
return True
diff --git a/tests/_data/mocks.py b/tests/_data/mocks.py
index 7da2ed275d..b759d93d90 100644
--- a/tests/_data/mocks.py
+++ b/tests/_data/mocks.py
@@ -20,6 +20,7 @@ EAGER_LIBS: list[DFType] = ["pandas", "polars", "pyarrow"]
def create_dataframes(
data: dict[str, Sequence[Any]],
+ *,
include: Optional[list[DFType]] = None,
exclude: Optional[list[DFType]] = None,
strict: bool = True,
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 6f3d997ddc..a80a056efe 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -136,10 +136,7 @@ class TestDataframes:
subject = ui.dataframe(df, page_size=1)
result = subject._get_dataframe(EmptyArgs())
assert result.total_rows == 3
- assert (
- result.url
- == "data:application/json;base64,W3siMSI6MSwiMiI6ImEifV0="
- )
+ assert result.url == '[{"1":1,"2":"a"}]'
# search
search_result = subject._search(
SearchTableArgs(page_size=1, page_number=0)
@@ -151,10 +148,7 @@ class TestDataframes:
subject = ui.dataframe(df, page_size=2)
result = subject._get_dataframe(EmptyArgs())
assert result.total_rows == 3
- assert (
- result.url
- == "data:application/json;base64,W3siMSI6MSwiMiI6ImEifSx7IjEiOjIsIjIiOiJhIn1d"
- )
+ assert result.url == '[{"1":1,"2":"a"},{"1":2,"2":"a"}]'
# search
search_result = subject._search(
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 2d73a88671..80358e3a9a 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
import unittest
from datetime import date
from typing import Any
@@ -748,7 +749,7 @@ class TestColumnarDefaultTable(unittest.TestCase):
"b": [3, 4],
}
)
- assert manager.to_json() == b'[{"a":1,"b":3},{"a":2,"b":4}]'
+ assert manager.to_json() == b'[{"a": 1, "b": 3}, {"a": 2, "b": 4}]'
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
@@ -879,13 +880,6 @@ class TestDictionaryDefaultTable(unittest.TestCase):
"b": 2,
}
- assert DefaultTableManager(self.manager.to_data()).apply_formatting(
- {"value": lambda x: x + 1}
- ).data == [
- {"key": "a", "value": 2},
- {"key": "b", "value": 3},
- ]
-
def test_apply_formatting_empty(self) -> None:
formatted_manager = self.manager.apply_formatting({})
assert formatted_manager.data == self.manager.data
@@ -916,7 +910,7 @@ class TestDictionaryDefaultTable(unittest.TestCase):
# Test converted to rows formatting
formatted_data = (
- DefaultTableManager(manager.to_data())
+ DefaultTableManager(json.loads(manager.to_json_str()))
.apply_formatting(
{"value": lambda x: "N/A" if x is None else x * 2}
)
@@ -963,7 +957,7 @@ class TestDictionaryDefaultTable(unittest.TestCase):
def test_to_json(self) -> None:
assert (
self.manager.to_json()
- == b'[{"key":"a","value":1},{"key":"b","value":2}]'
+ == b'[{"key": "a", "value": 1}, {"key": "b", "value": 2}]'
)
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index b4e86c8401..8156e184a4 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -25,6 +25,7 @@ from marimo._plugins.ui._impl.utils.dataframe import TableData
from marimo._runtime.functions import EmptyArgs
from marimo._runtime.runtime import Kernel
from marimo._utils.data_uri import from_data_uri
+from marimo._utils.platform import is_windows
from tests._data.mocks import create_dataframes
if TYPE_CHECKING:
@@ -543,7 +544,9 @@ def test_value_with_cell_selection_then_sorting_dict_of_lists() -> None:
]
[email protected]("df", create_dataframes({"a": [1, 2, 3]}, ["ibis"]))
+ "df", create_dataframes({"a": [1, 2, 3]}, include=["ibis"])
+)
def test_value_with_cell_selection_unsupported_for_ibis(df: Any) -> None:
with pytest.raises(NotImplementedError):
_table = ui.table(df, selection="multi-cell")
@@ -712,7 +715,7 @@ def test_table_with_too_many_rows_gets_clamped() -> None:
assert table._component_args["pagination"] is True
assert table._component_args["page-size"] == 10
assert table._component_args["total-rows"] == 20_002
- assert len(table._component_args["data"]) == 10
+ assert len(json.loads(table._component_args["data"])) == 10
def test_table_too_large_pagesize_throws_error() -> None:
@@ -731,9 +734,10 @@ def test_can_get_second_page() -> None:
page_number=1,
)
)
- assert len(result.data) == 10
- assert result.data[0]["a"] == 10
- assert result.data[-1]["a"] == 19
+ result_data = json.loads(result.data)
+ assert len(result_data) == 10
+ assert result_data[0]["a"] == 10
+ assert result_data[-1]["a"] == 19
def test_can_get_second_page_with_search() -> None:
@@ -746,18 +750,17 @@ def test_can_get_second_page_with_search() -> None:
page_number=1,
)
)
- assert len(result.data) == 5
- assert result.data[0]["a"] == 23
- assert result.data[-1]["a"] == 27
+ result_data = json.loads(result.data)
+ assert len(result_data) == 5
+ assert result_data[0]["a"] == 23
+ assert result_data[-1]["a"] == 27
@pytest.mark.parametrize(
"df",
- create_dataframes({"a": list(range(40))}, ["ibis"]),
+ create_dataframes({"a": list(range(40))}, include=["ibis"]),
)
def test_can_get_second_page_with_search_df(df: Any) -> None:
- import polars as pl
-
table = ui.table(df)
result = table._search(
SearchTableArgs(
@@ -766,12 +769,10 @@ def test_can_get_second_page_with_search_df(df: Any) -> None:
page_number=1,
)
)
- mime_type, data = from_data_uri(result.data)
- assert mime_type == "application/json"
- data = pl.read_json(data)
- assert len(data) == 5
- assert int(data["a"][0]) == 23
- assert int(data["a"][-1]) == 27
+ result_data = json.loads(result.data)
+ assert len(result_data) == 5
+ assert int(result_data[0]["a"]) == 23
+ assert int(result_data[-1]["a"]) == 27
def test_with_no_pagination() -> None:
@@ -780,7 +781,7 @@ def test_with_no_pagination() -> None:
assert table._component_args["pagination"] is False
assert table._component_args["page-size"] == 20
assert table._component_args["total-rows"] == 20
- assert len(table._component_args["data"]) == 20
+ assert len(json.loads(table._component_args["data"])) == 20
def test_table_with_too_many_rows_and_custom_total() -> None:
@@ -791,7 +792,7 @@ def test_table_with_too_many_rows_and_custom_total() -> None:
assert table._component_args["pagination"] is True
assert table._component_args["page-size"] == 10
assert table._component_args["total-rows"] == 300
- assert len(table._component_args["data"]) == 10
+ assert len(json.loads(table._component_args["data"])) == 10
def test_table_with_too_many_rows_unknown_total() -> None:
@@ -804,7 +805,7 @@ def test_table_with_too_many_rows_unknown_total() -> None:
assert table._component_args["pagination"] is True
assert table._component_args["page-size"] == 10
assert table._component_args["total-rows"] == "too_many"
- assert len(table._component_args["data"]) == 10
+ assert len(json.loads(table._component_args["data"])) == 10
def test_empty_table() -> None:
@@ -851,6 +852,7 @@ def test_with_too_many_rows_column_charts_disabled() -> None:
assert charts_enabled.is_disabled is False
[email protected](is_windows(), reason=r"windows returns \r instead")
def test__get_column_summaries_after_search() -> None:
data = {"a": list(range(20))}
table = ui.table(data)
@@ -865,7 +867,9 @@ def test__get_column_summaries_after_search() -> None:
)
summaries = table._get_column_summaries(EmptyArgs())
assert summaries.is_disabled is False
- assert summaries.data == [{"a": 2}, {"a": 12}]
+ summaries_data = from_data_uri(summaries.data)[1].decode("utf-8")
+ # Result is csv or json
+ assert summaries_data in ["a\n2\n12\n", '[{"a": 2}, {"a": 12}]']
# We don't have column summaries for non-dataframe data
assert summaries.summaries[0].min is None
assert summaries.summaries[0].max is None
@@ -881,7 +885,11 @@ def test__get_column_summaries_after_search_df() -> None:
summaries = table._get_column_summaries(EmptyArgs())
assert summaries.is_disabled is False
assert isinstance(summaries.data, str)
- assert summaries.data.startswith("data:application/json;base64,")
+ assert summaries.data.startswith(
+ "data:text/plain;base64,"
+ ) or summaries.data.startswith(
+ "data:application/vnd.apache.arrow.file;base64,"
+ )
assert summaries.summaries[0].min == 0
assert summaries.summaries[0].max == 19
@@ -896,7 +904,12 @@ def test__get_column_summaries_after_search_df() -> None:
summaries = table._get_column_summaries(EmptyArgs())
assert summaries.is_disabled is False
assert isinstance(summaries.data, str)
- assert summaries.data.startswith("data:application/json;base64,")
+ # Result is csv
+ assert summaries.data.startswith(
+ "data:text/csv;base64,"
+ ) or summaries.data.startswith(
+ "data:application/vnd.apache.arrow.file;base64,"
+ )
# We don't have column summaries for non-dataframe data
assert summaries.summaries[0].min == 2
assert summaries.summaries[0].max == 12
@@ -1010,6 +1023,38 @@ def test_show_column_summaries_default():
assert table_true._component_args["show-column-summaries"] is True
+def test_data_with_rich_components():
+ data = {
+ "a": [1, 2],
+ "b": [ui.text("foo"), ui.slider(start=0, stop=10)],
+ }
+ table = ui.table(data)
+ assert isinstance(table._component_args["data"], str)
+ assert isinstance(
+ json.loads(table._component_args["data"]),
+ list,
+ )
+
+
+ "df",
+ create_dataframes(
+ {
+ "a": [1, 2],
+ "b": [ui.text("foo"), ui.slider(start=0, stop=10)],
+ },
+ include=["polars", "pandas"],
+ ),
+)
+def test_data_with_rich_components_in_data_frames(df: Any) -> None:
+ table = ui.table(df)
+ assert isinstance(table._component_args["data"], str)
+ assert isinstance(
+ json.loads(table._component_args["data"]),
+ list,
+ )
+
+
def test_show_column_summaries_explicit():
# Test explicit setting of show_column_summaries
data = {"a": [1, 2, 3], "b": [4, 5, 6]}
@@ -1182,28 +1227,28 @@ def test_pagination_behavior() -> None:
table = ui.table(data)
assert table._component_args["pagination"] is False
assert table._component_args["page-size"] == 10
- assert len(table._component_args["data"]) == 8
+ assert len(json.loads(table._component_args["data"])) == 8
# Test with custom page_size=5 and data <= page_size
data = {"a": list(range(5))}
table = ui.table(data, page_size=5)
assert table._component_args["pagination"] is False
assert table._component_args["page-size"] == 5
- assert len(table._component_args["data"]) == 5
+ assert len(json.loads(table._component_args["data"])) == 5
# Test with custom page_size=5 and data > page_size
data = {"a": list(range(8))}
table = ui.table(data, page_size=5)
assert table._component_args["pagination"] is True
assert table._component_args["page-size"] == 5
- assert len(table._component_args["data"]) == 5
+ assert len(json.loads(table._component_args["data"])) == 5
# Test with explicit pagination=True
data = {"a": list(range(5))}
table = ui.table(data, pagination=True, page_size=5)
assert table._component_args["pagination"] is True
assert table._component_args["page-size"] == 5
- assert len(table._component_args["data"]) == 5
+ assert len(json.loads(table._component_args["data"])) == 5
def test_column_clamping():
@@ -1214,21 +1259,21 @@ def test_column_clamping():
table = ui.table(data)
assert len(table._manager.get_column_names()) == 100
assert table._component_args["total-columns"] == 100
- assert len(table._component_args["data"][0].keys()) == 50
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 50
assert table._component_args["field-types"] is None
# Test custom max_columns
table = ui.table(data, max_columns=20)
assert len(table._manager.get_column_names()) == 100
assert table._component_args["total-columns"] == 100
- assert len(table._component_args["data"][0].keys()) == 20
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 20
assert table._component_args["field-types"] is None
# Test no clamping
table = ui.table(data, max_columns=None)
assert len(table._manager.get_column_names()) == 100
assert table._component_args["total-columns"] == 100
- assert len(table._component_args["data"][0].keys()) == 100
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 100
assert table._component_args["field-types"] is None
@@ -1239,7 +1284,7 @@ def test_column_clamping_with_small_data():
table = ui.table(data)
assert len(table._manager.get_column_names()) == 10
assert table._component_args["total-columns"] == 10
- assert len(table._component_args["data"][0].keys()) == 10
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 10
assert table._component_args["field-types"] is None
@@ -1252,7 +1297,8 @@ def test_search_clamping_columns():
response = table._search(search_args)
# Check that the search result is clamped
- assert len(response.data[0].keys()) == 20
+ result_data = json.loads(response.data)
+ assert len(result_data[0].keys()) == 20
# Check that selection is not clamped
table._selected_manager = table._searched_manager.select_rows([0])
@@ -1269,7 +1315,8 @@ def test_search_no_clamping_columns():
response = table._search(search_args)
# Check that the search result is not clamped
- assert len(response.data[0].keys()) == 100
+ result_data = json.loads(response.data)
+ assert len(result_data[0].keys()) == 100
# Check that selection is not clamped
table._selected_manager = table._searched_manager.select_rows([0])
@@ -1284,7 +1331,7 @@ def test_column_clamping_with_exact_max_columns():
# Check that the table is not clamped
assert len(table._manager.get_column_names()) == 50
assert table._component_args["total-columns"] == 50
- assert len(table._component_args["data"][0].keys()) == 50
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 50
assert table._component_args["field-types"] is None
@@ -1295,7 +1342,7 @@ def test_column_clamping_with_more_than_max_columns():
# Check that the table is clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- assert len(table._component_args["data"][0].keys()) == 50
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 50
assert table._component_args["field-types"] is None
@@ -1305,7 +1352,7 @@ def test_column_clamping_with_no_columns():
# Check that the table handles no columns gracefully
assert len(table._manager.get_column_names()) == 1
assert table._component_args["total-columns"] == 1
- assert len(table._component_args["data"]) == 0
+ assert len(json.loads(table._component_args["data"])) == 0
assert table._component_args["field-types"] is None
@@ -1316,7 +1363,7 @@ def test_column_clamping_with_single_column():
# Check that the table handles a single column gracefully
assert len(table._manager.get_column_names()) == 1
assert table._component_args["total-columns"] == 1
- assert len(table._component_args["data"][0].keys()) == 1
+ assert len(json.loads(table._component_args["data"])[0].keys()) == 1
assert table._component_args["field-types"] is None
@@ -1332,8 +1379,7 @@ def test_column_clamping_with_polars():
# Check that the table is clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(table._component_args["data"])
headers = json_data[0].keys()
assert len(headers) == 50 # 50 columns
assert len(table._component_args["field-types"]) == 50
@@ -1343,8 +1389,7 @@ def test_column_clamping_with_polars():
# Check that the table is clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(table._component_args["data"])
headers = json_data[0].keys()
assert len(headers) == 40 # 40 columns
assert len(table._component_args["field-types"]) == 40
@@ -1354,8 +1399,7 @@ def test_column_clamping_with_polars():
# Check that the table is not clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(table._component_args["data"])
headers = json_data[0].keys()
assert len(headers) == 61 # 60 columns + 1 selection column
@@ -1479,8 +1523,7 @@ def test_json_multi_col_idx_table() -> None:
data = pd.DataFrame([(1, 1), (0, 1)], index=idx, columns=cols)
table = ui.table(data)
- json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(table._component_args["data"])
assert json_data == [
{
"": "All",
@@ -1504,8 +1547,7 @@ def test_json_multi_col_idx_table() -> None:
}
)
table = ui.table(df)
- json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(table._component_args["data"])
assert json_data == [
{
INDEX_COLUMN_NAME: 0,
@@ -1562,8 +1604,7 @@ def test_lazy_dataframe() -> None:
assert search_response.total_rows == "too_many"
# Check that only the preview rows are returned
- json_data = from_data_uri(search_response.data)[1].decode("utf-8")
- json_data = json.loads(json_data)
+ json_data = json.loads(search_response.data)
assert len(json_data) == num_rows
# Warning comes from search
@@ -1596,7 +1637,9 @@ def test_lazy_dataframe_with_non_lazy_dataframe():
def test_get_data_url_no_deps() -> None:
table = ui.table([1, 2, 3])
response = table._get_data_url({})
- assert response.data_url == [{"value": 1}, {"value": 2}, {"value": 3}]
+ assert response.data_url.startswith("data:application/json;base64,")
+ data = json.loads(from_data_uri(response.data_url)[1])
+ assert data == [{"value": 1}, {"value": 2}, {"value": 3}]
assert response.format == "json"