|
1 | 1 | # Copyright 2024 Marimo. All rights reserved. |
2 | 2 | from __future__ import annotations |
3 | 3 |
|
4 | | -from typing import ( |
5 | | - TypeVar, |
6 | | - Union, |
7 | | -) |
| 4 | +from typing import Any, TypeVar, Union |
8 | 5 |
|
9 | 6 | from narwhals.typing import IntoDataFrame |
10 | 7 |
|
11 | 8 | from marimo import _loggers |
| 9 | +from marimo._output.data import data as mo_data |
12 | 10 | from marimo._output.mime import MIME |
13 | 11 | from marimo._plugins.core.web_component import JSONType |
| 12 | +from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME |
| 13 | +from marimo._plugins.ui._impl.tables.table_manager import TableManager |
14 | 14 |
|
15 | 15 | LOGGER = _loggers.marimo_logger() |
16 | 16 |
|
|
26 | 26 | dict[str, ListOrTuple[JSONType]], |
27 | 27 | IntoDataFrame, |
28 | 28 | ] |
| 29 | + |
| 30 | + |
| 31 | +def download_as( |
| 32 | + manager: TableManager[Any], ext: str, drop_marimo_index: bool = False |
| 33 | +) -> str: |
| 34 | + """Download the table data in the specified format. |
| 35 | +
|
| 36 | + Args: |
| 37 | + manager (TableManager[Any]): The table manager to download. |
| 38 | + ext (str): The format to download the table data in. |
| 39 | + drop_marimo_index (bool, optional): Whether to drop the marimo selection column. |
| 40 | + Defaults to False. |
| 41 | +
|
| 42 | + Raises: |
| 43 | + ValueError: If unrecognized format. |
| 44 | + NotImplementedError: If the table format is not supported. |
| 45 | +
|
| 46 | + Returns: |
| 47 | + str: The URL to download the table data. |
| 48 | + """ |
| 49 | + if drop_marimo_index: |
| 50 | + # Remove the selection column if exists |
| 51 | + manager = manager.drop_columns([INDEX_COLUMN_NAME]) |
| 52 | + |
| 53 | + if ext == "csv": |
| 54 | + return mo_data.csv(manager.to_csv()).url |
| 55 | + elif ext == "json": |
| 56 | + return mo_data.json(manager.to_json()).url |
| 57 | + elif ext == "parquet": |
| 58 | + return mo_data.parquet(manager.to_parquet()).url |
| 59 | + else: |
| 60 | + raise ValueError("format must be one of 'csv', 'json', or 'parquet'.") |
0 commit comments