cirro.models.form_specification

 1from typing import Dict, Any, List
 2
 3import jsonschema
 4from cirro_api_client.v1.models import FormSchema
 5
 6
 7def _get_fields_in_schema(schema: Dict, parent_path='') -> List['Parameter']:
 8    # This breaks for more advanced json schema usages such as the if/then
 9    fields = []
10
11    for [field_key, field_spec] in schema.items():
12        field_path = field_key if parent_path == '' else f'{parent_path}.{field_key}'
13        field = Parameter(field_key, field_spec, field_path)
14        fields.append(field)
15
16        if 'properties' in field_spec:
17            fields.extend(_get_fields_in_schema(field_spec['properties'], field_path))
18
19    return fields
20
21
22class ParameterSpecification:
23    """
24    Used to describe parameters used in a process (uses JSONSchema)
25    """
26    def __init__(self, form_schema: FormSchema):
27        self._form_spec_raw: Dict = form_schema.form.additional_properties
28        self._form_spec_ui: Dict = form_schema.ui.additional_properties
29        self.form_spec = _get_fields_in_schema(self._form_spec_raw.get('properties') or {})
30
31    @property
32    def form_spec_json(self) -> dict:
33        """
34        Returns the JSON schema of the form specification
35        """
36        return self._form_spec_raw
37
38    def validate_params(self, params: Dict):
39        """
40        Validates that the given parameters conforms to the specification
41        """
42        try:
43            jsonschema.validate(instance=params, schema=self._form_spec_raw)
44        except jsonschema.ValidationError as e:
45            raise RuntimeError(f'Parameter at {e.json_path} error: {e.message}') from e
46
47    def print(self):
48        """
49        Prints out a user-friendly view of the parameters
50        """
51        print("Parameters:")
52        for field in self.form_spec:
53            tab_prefix = '\t' * (field.path.count('.') + 1)
54            print(tab_prefix + str(field))
55
56
57class Parameter:
58    def __init__(self, key: str, spec: Dict[str, Any], path: str):
59        self.spec = spec
60        self.key = key
61        self.path = path
62
63    @property
64    def is_group(self):
65        return self.spec.get('type') == 'object'
66
67    def __str__(self):
68        display_value = ''
69        additional_data = ''
70
71        if self.spec.get('title'):
72            display_value += f'{self.spec.get("title")}'
73            additional_data += f'key={self.key}, '
74        else:
75            display_value += self.key
76
77        for prop in ['default', 'type', 'enum', 'description']:
78            if prop_value := self.spec.get(prop):
79                additional_data += f'{prop}={prop_value}, '
80
81        if additional_data and not self.is_group:
82            display_value += f' ({additional_data.rstrip(", ")})'
83
84        if self.is_group:
85            display_value += ' (Group)'
86        return display_value
class ParameterSpecification:
23class ParameterSpecification:
24    """
25    Used to describe parameters used in a process (uses JSONSchema)
26    """
27    def __init__(self, form_schema: FormSchema):
28        self._form_spec_raw: Dict = form_schema.form.additional_properties
29        self._form_spec_ui: Dict = form_schema.ui.additional_properties
30        self.form_spec = _get_fields_in_schema(self._form_spec_raw.get('properties') or {})
31
32    @property
33    def form_spec_json(self) -> dict:
34        """
35        Returns the JSON schema of the form specification
36        """
37        return self._form_spec_raw
38
39    def validate_params(self, params: Dict):
40        """
41        Validates that the given parameters conforms to the specification
42        """
43        try:
44            jsonschema.validate(instance=params, schema=self._form_spec_raw)
45        except jsonschema.ValidationError as e:
46            raise RuntimeError(f'Parameter at {e.json_path} error: {e.message}') from e
47
48    def print(self):
49        """
50        Prints out a user-friendly view of the parameters
51        """
52        print("Parameters:")
53        for field in self.form_spec:
54            tab_prefix = '\t' * (field.path.count('.') + 1)
55            print(tab_prefix + str(field))

Used to describe parameters used in a process (uses JSONSchema)

ParameterSpecification(form_schema: cirro_api_client.v1.models.FormSchema)
27    def __init__(self, form_schema: FormSchema):
28        self._form_spec_raw: Dict = form_schema.form.additional_properties
29        self._form_spec_ui: Dict = form_schema.ui.additional_properties
30        self.form_spec = _get_fields_in_schema(self._form_spec_raw.get('properties') or {})
form_spec
form_spec_json: dict
32    @property
33    def form_spec_json(self) -> dict:
34        """
35        Returns the JSON schema of the form specification
36        """
37        return self._form_spec_raw

Returns the JSON schema of the form specification

def validate_params(self, params: Dict):
39    def validate_params(self, params: Dict):
40        """
41        Validates that the given parameters conforms to the specification
42        """
43        try:
44            jsonschema.validate(instance=params, schema=self._form_spec_raw)
45        except jsonschema.ValidationError as e:
46            raise RuntimeError(f'Parameter at {e.json_path} error: {e.message}') from e

Validates that the given parameters conforms to the specification

def print(self):
48    def print(self):
49        """
50        Prints out a user-friendly view of the parameters
51        """
52        print("Parameters:")
53        for field in self.form_spec:
54            tab_prefix = '\t' * (field.path.count('.') + 1)
55            print(tab_prefix + str(field))

Prints out a user-friendly view of the parameters

class Parameter:
58class Parameter:
59    def __init__(self, key: str, spec: Dict[str, Any], path: str):
60        self.spec = spec
61        self.key = key
62        self.path = path
63
64    @property
65    def is_group(self):
66        return self.spec.get('type') == 'object'
67
68    def __str__(self):
69        display_value = ''
70        additional_data = ''
71
72        if self.spec.get('title'):
73            display_value += f'{self.spec.get("title")}'
74            additional_data += f'key={self.key}, '
75        else:
76            display_value += self.key
77
78        for prop in ['default', 'type', 'enum', 'description']:
79            if prop_value := self.spec.get(prop):
80                additional_data += f'{prop}={prop_value}, '
81
82        if additional_data and not self.is_group:
83            display_value += f' ({additional_data.rstrip(", ")})'
84
85        if self.is_group:
86            display_value += ' (Group)'
87        return display_value
Parameter(key: str, spec: Dict[str, Any], path: str)
59    def __init__(self, key: str, spec: Dict[str, Any], path: str):
60        self.spec = spec
61        self.key = key
62        self.path = path
spec
key
path
is_group
64    @property
65    def is_group(self):
66        return self.spec.get('type') == 'object'