Skip to content

Validators

chart_checkbox(value)

A validator for checkbox.

In a checkbox form snippet we have two inputs, one hidden and one checkbox. The hidden input always sends a value of "off" and the checkbox sends "on"

We need it to properly set a default True value for the field.

PARAMETER DESCRIPTION
value

The checkbox(s) value(s)

TYPE: str | list[str]

RETURNS DESCRIPTION
bool

The value as a boolean

TYPE: str

Source code in ckanext/charts/logic/validators.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def chart_checkbox(value: str | list[str]) -> str:
    """A validator for checkbox.

    In a checkbox form snippet we have two inputs, one hidden and one checkbox.
    The hidden input always sends a value of "off" and the checkbox sends "on"

    We need it to properly set a default `True` value for the field.

    Args:
        value (str | list[str]): The checkbox(s) value(s)

    Returns:
        bool: The value as a boolean
    """
    if isinstance(value, list):
        return value[-1]

    return value

charts_if_empty_same_as(other_key)

A custom version of if_empty_same_as validator for charts.

This validator is used to set the value of a field to the value of another field if it is empty or missing.

PARAMETER DESCRIPTION
other_key

The key of the field to copy the value from

TYPE: str

RETURNS DESCRIPTION
Callable[..., Any]

Callable[..., Any]: The validator function

Source code in ckanext/charts/logic/validators.py
28
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
54
def charts_if_empty_same_as(other_key: str) -> Callable[..., Any]:
    """A custom version of if_empty_same_as validator for charts.

    This validator is used to set the value of a field to the value of another
    field if it is empty or missing.

    Args:
        other_key (str): The key of the field to copy the value from

    Returns:
        Callable[..., Any]: The validator function
    """

    def callable(
        key: types.FlattenKey,
        data: types.FlattenDataDict,
        errors: types.FlattenErrorDict,
        context: types.Context,
    ) -> None:
        value = data.get(key)
        if not value or value is tk.missing:
            try:
                data[key] = data[key[:-1] + (other_key,)]
            except KeyError:
                data[key] = data.get(("__extras",), {}).get(other_key, "")

    return callable

charts_list_length_validator(max_length)

A validator to check the length of a list.

PARAMETER DESCRIPTION
max_length

The maximum length of the list

TYPE: int

RETURNS DESCRIPTION
Callable[..., Any]

Callable[..., Any]: The validator function

Source code in ckanext/charts/logic/validators.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def charts_list_length_validator(max_length: int) -> Callable[..., Any]:
    """A validator to check the length of a list.

    Args:
        max_length (int): The maximum length of the list

    Returns:
        Callable[..., Any]: The validator function
    """

    def callable(
        key: types.FlattenKey,
        data: types.FlattenDataDict,
        errors: types.FlattenErrorDict,
        context: types.Context,
    ):
        if len(data[key]) > max_length:
            raise tk.Invalid(tk._("Length must be less than {0}").format(max_length))

    return callable

charts_list_to_csv(data)

Convert a list of strings to a CSV string.

PARAMETER DESCRIPTION
data

The data to convert

TYPE: list[str] | str

RETURNS DESCRIPTION
str

The comma separated string

TYPE: str

Source code in ckanext/charts/logic/validators.py
160
161
162
163
164
165
166
167
168
169
170
171
172
def charts_list_to_csv(data: list[str] | str) -> str:
    """Convert a list of strings to a CSV string.

    Args:
        data (list[str] | str): The data to convert

    Returns:
        str: The comma separated string
    """
    if not isinstance(data, list):
        return data

    return ", ".join(data)

charts_strategy_support(strategy)

Check if the cache strategy is supported.

PARAMETER DESCRIPTION
strategy

The cache strategy

TYPE: str

RETURNS DESCRIPTION
str

The cache strategy if it is supported

TYPE: str

RAISES DESCRIPTION
Invalid

If the cache strategy is not supported

Source code in ckanext/charts/logic/validators.py
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
def charts_strategy_support(strategy: str) -> str:
    """Check if the cache strategy is supported.

    Args:
        strategy (str): The cache strategy

    Returns:
        str: The cache strategy if it is supported

    Raises:
        tk.Invalid: If the cache strategy is not supported
    """
    if strategy not in const.SUPPORTED_CACHE_STRATEGIES:
        raise tk.Invalid(tk._("Invalid cache strategy"))

    if strategy == const.CACHE_FILE_ORC:
        try:
            from pyarrow import orc as _  # noqa
        except ImportError:
            raise tk.Invalid(
                tk._("Can't use File Orc cache strategy. PyArrow is not installed"),
            ) from None

    if not strategy:
        return const.DEFAULT_CACHE_STRATEGY

    return strategy

charts_to_list_if_string(value)

Convert a string to a list.

PARAMETER DESCRIPTION
value

The value to convert

TYPE: Any

RETURNS DESCRIPTION
Any

list[Any]: The value in a list

Source code in ckanext/charts/logic/validators.py
145
146
147
148
149
150
151
152
153
154
155
156
157
def charts_to_list_if_string(value: Any) -> Any:
    """Convert a string to a list.

    Args:
        value (Any): The value to convert

    Returns:
        list[Any]: The value in a list
    """
    if isinstance(value, str):
        return [value]

    return value

charts_validate_extras(key, data, errors, context)

Validate charts settings according to the chart type and engine schema.

PARAMETER DESCRIPTION
key

The key of the field

TYPE: FlattenKey

data

The data to validate

TYPE: FlattenDataDict

errors

The errors dict

TYPE: FlattenErrorDict

context

The context

TYPE: Context

Source code in ckanext/charts/logic/validators.py
 86
 87
 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
def charts_validate_extras(
    key: types.FlattenKey,
    data: types.FlattenDataDict,
    errors: types.FlattenErrorDict,
    context: types.Context,
) -> None:
    """Validate charts settings according to the chart type and engine schema.

    Args:
        key (types.FlattenKey): The key of the field
        data (types.FlattenDataDict): The data to validate
        errors (types.FlattenErrorDict): The errors dict
        context (types.Context): The context
    """
    settings = _extract_setting(data)

    if "engine" not in settings or "type" not in settings:
        builder = DEFAULT_CHART_FORM(
            resource_id=settings["resource_id"],
            resource_view_id=settings.get("id"),
        )
    else:
        builder = utils.get_chart_form_builder(
            settings["engine"],
            settings["type"],
            resource_id=settings["resource_id"],
            resource_view_id=settings.get("id"),
        )

    settings, err = tk.navl_validate(
        settings,
        builder.get_validation_schema(
            context.get("_for_show", False),
        ),
        {},
    )

    # TODO: do we have a better way to handle this? Seems like a hack
    for k, v in settings.items():
        data[(k,)] = v

    for k, v in settings.pop("__extras", {}).items():
        data[(k,)] = v

    for k, v in err.items():
        errors[(k,)] = v

float_validator(value)

A validator for decimal numbers.

PARAMETER DESCRIPTION
value

The value to validate

TYPE: Any

RETURNS DESCRIPTION
float

The value as a float

TYPE: float

Source code in ckanext/charts/logic/validators.py
13
14
15
16
17
18
19
20
21
22
23
24
25
def float_validator(value: Any) -> float:
    """A validator for decimal numbers.

    Args:
        value (Any): The value to validate

    Returns:
        float: The value as a float
    """
    try:
        return float(value)
    except ValueError:
        raise tk.Invalid(tk._("Must be a decimal number")) from None