Skip to content

Utility Functions

build_chart_for_data(settings, data)

Build chart for the given dataframe and settings.

PARAMETER DESCRIPTION
settings

Chart settings

TYPE: dict[str, Any]

data

Dataframe with data

TYPE: DataFrame

RETURNS DESCRIPTION
str | None

Chart config as JSON string

Source code in ckanext/charts/utils.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def build_chart_for_data(settings: dict[str, Any], data: pd.DataFrame) -> str | None:
    """Build chart for the given dataframe and settings.

    Args:
        settings: Chart settings
        data: Dataframe with data

    Returns:
        Chart config as JSON string
    """

    builder = get_chart_form_builder(
        settings["engine"],
        settings["type"],
        dataframe=data,
    )

    settings, _ = tk.navl_validate(settings, builder.get_validation_schema(), {})

    return _build_chart(settings, data)

build_chart_for_resource(settings, resource_id, resource_view_id=None)

Build chart for the given resource ID.

Uses a DatastoreDataFetcher to fetch data from the resource.

PARAMETER DESCRIPTION
settings

Chart settings

TYPE: dict[str, Any]

resource_id

Resource ID

TYPE: str

RETURNS DESCRIPTION
str | None

str | None: Chart config as JSON string or None if the chart can't be built

Source code in ckanext/charts/utils.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def build_chart_for_resource(
    settings: dict[str, Any],
    resource_id: str,
    resource_view_id: str | None = None,
) -> str | None:
    """Build chart for the given resource ID.

    Uses a DatastoreDataFetcher to fetch data from the resource.

    Args:
        settings: Chart settings
        resource_id: Resource ID

    Returns:
        str | None: Chart config as JSON string or None if the chart can't be built
    """
    settings.pop("__extras", None)

    try:
        df = DatastoreDataFetcher(
            resource_id,
            resource_view_id,
            settings=settings,
        ).fetch_data()
    except tk.ValidationError:
        return None

    return _build_chart(settings, df)

can_view(data_dict)

Check if the resource can be viewed as a chart.

For now, we work only with resources stored with the DataStore.

PARAMETER DESCRIPTION
data_dict

Resource data dictionary

TYPE: dict[str, Any]

RETURNS DESCRIPTION
bool

True if the resource can be viewed as a chart, False otherwise

TYPE: bool

Source code in ckanext/charts/utils.py
181
182
183
184
185
186
187
188
189
190
191
192
def can_view(data_dict: dict[str, Any]) -> bool:
    """Check if the resource can be viewed as a chart.

    For now, we work only with resources stored with the DataStore.

    Args:
        data_dict: Resource data dictionary

    Returns:
        bool: True if the resource can be viewed as a chart, False otherwise
    """
    return data_dict["resource"].get("datastore_active")

get_chart_form_builder(engine, chart_type, **kwargs)

Get an instantiated form builder for the given engine and chart type.

PARAMETER DESCRIPTION
engine

Chart engine name

TYPE: str

chart_type

Chart type name

TYPE: str

**kwargs

Arguments to pass to the builder constructor (typically: resource_id, resource_view_id, settings)

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Any

An instance of the form builder class

RAISES DESCRIPTION
NotImplementedError

If engine is not supported

Example

builder = get_chart_form_builder( ... "plotly", ... "line", ... resource_id="abc123", ... settings={...}, ... )

Source code in ckanext/charts/utils.py
56
57
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
def get_chart_form_builder(
    engine: str,
    chart_type: str,
    **kwargs: Any,
) -> Any:
    """Get an instantiated form builder for the given engine and chart type.

    Args:
        engine: Chart engine name
        chart_type: Chart type name
        **kwargs: Arguments to pass to the builder constructor
                 (typically: resource_id, resource_view_id, settings)

    Returns:
        An instance of the form builder class

    Raises:
        NotImplementedError: If engine is not supported

    Example:
        >>> builder = get_chart_form_builder(
        ...     "plotly",
        ...     "line",
        ...     resource_id="abc123",
        ...     settings={...},
        ... )
    """
    builder_class = _get_chart_form_builder_class(engine, chart_type)
    return builder_class(**kwargs)

get_chart_view_ids(resource_id)

Return a list of chart-related ResourceView IDs for a given resource_id.

Source code in ckanext/charts/utils.py
205
206
207
208
209
210
211
212
213
214
215
def get_chart_view_ids(resource_id: str) -> list[str]:
    """Return a list of chart-related ResourceView IDs for a given resource_id."""
    return [
        view_id
        for (view_id,) in model.Session.query(model.ResourceView.id)
        .filter(
            model.ResourceView.resource_id == resource_id,
            model.ResourceView.view_type.in_({"charts_view", "charts_builder_view"}),
        )
        .all()
    ]

get_column_options(resource_id)

Get column options for the given resource.

PARAMETER DESCRIPTION
resource_id

Resource ID

TYPE: str

RETURNS DESCRIPTION
list[dict[str, str]]

List of column options

Source code in ckanext/charts/utils.py
17
18
19
20
21
22
23
24
25
26
def get_column_options(resource_id: str) -> list[dict[str, str]]:
    """Get column options for the given resource.

    Args:
        resource_id: Resource ID

    Returns:
        List of column options
    """
    return [{"text": col, "value": col} for col in get_datastore_column_names(resource_id)]

get_datastore_column_names(resource_id)

Retrieve column names from the datastore for the given resource ID.

RETURNS DESCRIPTION
list[str]

Column names from cache if available; otherwise, fetched

list[str]

from the datastore.

Source code in ckanext/charts/utils.py
195
196
197
198
199
200
201
202
def get_datastore_column_names(resource_id: str) -> list[str]:
    """Retrieve column names from the datastore for the given resource ID.

    Returns:
        Column names from cache if available; otherwise, fetched
        from the datastore.
    """
    return DatastoreDataFetcher(resource_id).get_all_column_names()

printable_file_size(size_bytes)

Convert file size in bytes to human-readable format.

PARAMETER DESCRIPTION
size_bytes

File size in bytes

TYPE: int

RETURNS DESCRIPTION
str

Human-readable file size

TYPE: str

Examples:

>>> printable_file_size(123456789)
'117.7 MB'
>>> printable_file_size(7777)
'7.6 KB'
Source code in ckanext/charts/utils.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def printable_file_size(size_bytes: int) -> str:
    """Convert file size in bytes to human-readable format.

    Args:
        size_bytes: File size in bytes

    Returns:
        str: Human-readable file size

    Examples:
        >>> printable_file_size(123456789)
        '117.7 MB'

        >>> printable_file_size(7777)
        '7.6 KB'
    """
    if size_bytes == 0:
        return "0 bytes"

    size_name = ("bytes", "KB", "MB", "GB", "TB")
    i = int(math.floor(math.log(size_bytes, 1024)))
    p = math.pow(1024, i)
    s = round(float(size_bytes) / p, 1)

    return f"{s} {size_name[i]}"