Skip to content

Helper Functions

CKAN helper functions are typically used in templates, but also available everywhere with toolkit.h.helper_name().

tables_get_columns_visibility_from_request()

Get the column visibility settings from the request arguments.

RETURNS DESCRIPTION
dict[str, bool]

A dictionary mapping column field names to their visibility state (True/False).

dict[str, bool]

Only hidden columns are included in the dictionary with False value.

Source code in ckanext/tables/helpers.py
44
45
46
47
48
49
50
51
def tables_get_columns_visibility_from_request() -> dict[str, bool]:
    """Get the column visibility settings from the request arguments.

    Returns:
        A dictionary mapping column field names to their visibility state (True/False).
        Only hidden columns are included in the dictionary with False value.
    """
    return dict.fromkeys(tk.request.args.getlist("hidden_column"), False)

tables_get_filters_from_request()

Get the filters from the request arguments.

RETURNS DESCRIPTION
list[FilterItem]

A dictionary of filters

Source code in ckanext/tables/helpers.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def tables_get_filters_from_request() -> list[t.FilterItem]:
    """Get the filters from the request arguments.

    Returns:
        A dictionary of filters
    """
    fields = tk.request.args.getlist("field")
    operators = tk.request.args.getlist("operator")
    values = tk.request.args.getlist("value")

    filters = []

    for field, op, value in zip(fields, operators, values):  # noqa: B905
        if not field or not op or not value:
            continue
        filters.append(t.FilterItem(field=field, operator=op, value=value))

    return filters

tables_guess_data_source(resource, resource_view)

Guess the appropriate data source for a resource.

PARAMETER DESCRIPTION
resource

The resource dictionary.

TYPE: dict[str, Any]

resource_view

Optional resource view dictionary. When it contains a file_url key that URL is used as the data source URL and its file extension is used to determine the format (overriding the resource format).

TYPE: dict[str, Any]

RETURNS DESCRIPTION
BaseDataSource

An instantiated data source ready to use.

Source code in ckanext/tables/helpers.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def tables_guess_data_source(
    resource: dict[str, Any],
    resource_view: dict[str, Any],
) -> t.BaseDataSource:
    """Guess the appropriate data source for a resource.

    Args:
        resource: The resource dictionary.
        resource_view: Optional resource view dictionary. When it contains a
            ``file_url`` key that URL is used as the data source URL and its
            file extension is used to determine the format (overriding the
            resource format).

    Returns:
        An instantiated data source ready to use.
    """
    file_url = resource_view.get("file_url", "")

    if resource.get("datastore_active") and not file_url:
        return t.DataStoreDataSource(resource_id=resource["id"])

    if file_url:
        url = file_url
        fmt = Path(file_url.split("?")[0]).suffix.lstrip(".").lower()
    else:
        url = resource.get("url")
        fmt = resource.get("format", "").lower()

    cache_backend = get_cache_backend()
    data_sources = {
        "csv": t.CsvUrlDataSource,
        "xlsx": t.XlsxUrlDataSource,
        "orc": t.OrcUrlDataSource,
        "parquet": t.ParquetUrlDataSource,
        "feather": t.FeatherUrlDataSource,
    }

    data_source_class = data_sources.get(fmt)

    if data_source_class:
        if file_url:
            return data_source_class(url=url, cache_backend=cache_backend)
        return data_source_class(url=url, resource=resource, cache_backend=cache_backend)

    raise ValueError(f"Unsupported format: {fmt}")  # noqa: TRY003

tables_init_temporary_preview_table(resource, resource_view)

Initialize a temporary preview table for a given resource.

PARAMETER DESCRIPTION
resource

The resource dictionary containing the URL and format of the data.

TYPE: dict[str, Any]

resource_view

Optional resource view dictionary. When it contains a file_url key that URL is used instead of the resource URL and the format is inferred from its file extension.

TYPE: dict[str, Any]

RETURNS DESCRIPTION
TableDefinition

A TableDefinition object representing the initialized temporary preview table.

Source code in ckanext/tables/helpers.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def tables_init_temporary_preview_table(
    resource: dict[str, Any],
    resource_view: dict[str, Any],
) -> t.TableDefinition:
    """Initialize a temporary preview table for a given resource.

    Args:
        resource: The resource dictionary containing the URL and format of the data.
        resource_view: Optional resource view dictionary. When it contains a
            ``file_url`` key that URL is used instead of the resource URL and
            the format is inferred from its file extension.

    Returns:
        A TableDefinition object representing the initialized temporary preview table.
    """
    data_source = tk.h.tables_guess_data_source(resource, resource_view)

    return t.TableDefinition(
        name=f"preview resource {resource['id']}",
        data_source=data_source,
        exporters=t.ALL_EXPORTERS,
        ajax_url=tk.url_for(
            "tables.resource_table_ajax",
            resource_id=resource["id"],
            resource_view_id=resource_view["id"],
        ),
        columns=[t.ColumnDefinition(field=col) for col in data_source.get_columns()],
    )

tables_json_dumps(value)

Convert a value to a JSON string.

PARAMETER DESCRIPTION
value

The value to convert to a JSON string

TYPE: Any

RETURNS DESCRIPTION
str

The JSON string

Source code in ckanext/tables/helpers.py
12
13
14
15
16
17
18
19
20
21
def tables_json_dumps(value: Any) -> str:
    """Convert a value to a JSON string.

    Args:
        value: The value to convert to a JSON string

    Returns:
        The JSON string
    """
    return json.dumps(value)