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
66
67
68
69
70
71
72
73
74
75
76
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
    """
    return _build_chart(settings, data)

build_chart_for_resource(settings, resource_id)

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def build_chart_for_resource(settings: dict[str, Any], resource_id: str) -> 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).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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
    """
    if data_dict["resource"].get("datastore_active"):
        return True

    # TODO: Add support for XML, XLS, XLSX, and other formats tabular data?
    # if data_dict["resource"]["format"].lower() == "xml":
    #     return True

    return False

get_chart_form_builder(engine, chart_type)

Get form builder for the given engine and chart type.

Source code in ckanext/charts/utils.py
56
57
58
59
60
61
62
63
def get_chart_form_builder(engine: str, chart_type: str):
    """Get form builder for the given engine and chart type."""
    builders = get_chart_engines()

    if engine not in builders:
        raise NotImplementedError(f"Engine {engine} is not supported")

    return builders[engine].get_form_for_type(chart_type)

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
15
16
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
    """
    df = DatastoreDataFetcher(resource_id).fetch_data()

    return [{"text": col, "value": col} for col in df.columns]

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]}"