Source code for ecpi.common.params.tools_check

'''
Created on ?

@author: Colley Jean-Marc, APC/IN2P3/CNRS
'''

import re
import json
import logging

from jsonschema import validate, validators, draft4_format_checker, Draft4Validator, _utils
from jsonschema.exceptions import ValidationError

s_logger = logging.getLogger(__name__)


[docs]def check_add_default_file(file_schema, d_pars): """ Open json schema and check if dictionary d_pars is compliant with it :param file_schema: json schema file :param d_pars: dictionary of parameters """ with open(file_schema, "r") as fichier: json_schem = json.load(fichier) return check_add_default_dict(json_schem, d_pars)
[docs]def check_add_default_dict(schema, d_pars): """Check only with json scheme """ for k in list(d_pars.keys()): if not k in list(schema['properties'].keys()): msg = f"\n\t#### Unknown parameter ['{k}'], not in json schema" msg += f" {sorted(list(schema['properties'].keys()))}" msg += f"\n\t#### Check the parameter name ['{k}'] in settings configuration file" s_logger.warning(msg) del d_pars[k] try: DefaultValidatingDraft4Validator(schema).validate(d_pars) except ValidationError as valid_err: s_logger.error(f"Validation KO: {valid_err}") return False s_logger.info("Parameters validated by json scheme") return True
[docs]def cfgparser_to_dict4json(cfg, section): """ a mettre dans common tools pour d'autres scripts energy_ranges = json.loads(cfg['general']['channels_ranges']) """ dict4json_section = {} dict_section = cfg._sections[section] s_logger.debug(dict_section) for key in dict_section.keys(): pval = cfg[section][key] new_val = pval try: # convention vers un nombre si possible new_val = float(pval) except: pass if pval[0] == '[': # print("pval:",pval) try: new_val = json.loads(pval) except: msg = f"pb with '{pval}', check number of '[' and ']' or if '\"' are present" s_logger.error(msg + " ie \"ECL-ABC-DEF\".") return None # print(new_val) dict4json_section[key] = new_val return dict4json_section
[docs]def extend_with_default(validator_class): """ a mettre dans common tools pour d'autres scripts see https://python-jsonschema.readthedocs.io/en/stable/faq/ for more informations """ validate_properties = validator_class.VALIDATORS["properties"] def set_defaults(validator, properties, instance, schema): ''' see https://python-jsonschema.readthedocs.io/en/stable/faq/ for more informations ''' # for k in list(instance.keys()): # if not k in list(properties.keys()): # del instance[k] # s_logger.warning(f"\n\t#### Key ['{k}'] not in schema keys {sorted(list(properties.keys()))}") for mproperty, subschema in properties.items(): if "default" in subschema: instance.setdefault(mproperty, subschema["default"]) for error in validate_properties( validator, properties, instance, schema, ): yield error return validators.extend( validator_class, {"properties" : set_defaults}, )
DefaultValidatingDraft4Validator = extend_with_default(Draft4Validator)