From c687960f1517f667d77840616f06da9cd3247a0b Mon Sep 17 00:00:00 2001 From: Emmanuel Garette Date: Tue, 5 Feb 2019 07:01:22 +0100 Subject: [PATCH] some improvements --- tiramisu_json_api/api.py | 130 ++++++++++++++++++++------------------- 1 file changed, 66 insertions(+), 64 deletions(-) diff --git a/tiramisu_json_api/api.py b/tiramisu_json_api/api.py index a5852d5..0da6843 100644 --- a/tiramisu_json_api/api.py +++ b/tiramisu_json_api/api.py @@ -20,12 +20,11 @@ class Option: # fake Option (IntOption, StrOption, ...) # only usefull for warnings def __init__(self, - name, path): - self.name = name self.path = path def __call__(self): + # suppose to be a weakref return self def impl_getpath(self): @@ -99,7 +98,7 @@ class TiramisuOptionOption: props.append('mandatory') if model.get('readOnly'): props.append('frozen') - if model.get('hidden'): + if self.config.get_hidden(this._path): props.append('hidden') if self.form.get(self._path, {}).get('clearable'): props.append('clearable') @@ -112,7 +111,9 @@ class TiramisuOptionOption: class TiramisuOptionProperty: # config.option(path).property def __init__(self, + path: str, model: Dict) -> None: + self.path = path self.model = model def get(self, only_raises=False): @@ -132,7 +133,7 @@ class TiramisuOptionProperty: properties.append('frozen') else: properties = [] - if self.model.get('hidden', False): + if self.config.get_hidden(self.path) properties.append('hidden') return properties @@ -156,7 +157,7 @@ class _Value: fullpath, withwarning) else: - value = self._get_value(key, schema) + value = self.config.get_value(key, schema) self._display_warnings(key, value, option['type'], option['name'], withwarning) ret[key] = value @@ -172,33 +173,22 @@ class _Value: return ret def _display_warnings(self, path, value, type, name, withwarning=True): - if self.model.get(path, {}).get('error'): - for err in self.model.get(path, {}).get('error'): - warnings.warn_explicit(ValueOptionError(value, - type, - Option(name, path), - '{0}'.format(err)), - ValueErrorWarning, - self.__class__.__name__, 0) + for err in self.model.get(path, {}).get('error', []): + warnings.warn_explicit(ValueOptionError(value, + type, + Option(path), + '{0}'.format(err)), + ValueErrorWarning, + self.__class__.__name__, 0) if withwarning and self.model.get(path, {}).get('warnings'): for warn in self.model.get(path, {}).get('warnings'): + # FIXME ValueWarning needs value and type attribute! warnings.warn_explicit(ValueWarning('{0}'.format(warn), - Option(name, path)), + Option(path)), ValueWarning, self.__class__.__name__, 0) - def _get_value(self, - path: str, - schema: Dict) -> Any: - if 'value' in self.temp.get(path, {}): - value = self.temp[path]['value'] - else: - value = self.model.get(path, {}).get('value') - if value is None and schema.get('isMulti', False): - value = [] - return value - class TiramisuOptionOwner: # config.option(path).owner @@ -219,12 +209,7 @@ class TiramisuOptionOwner: self.index = index def isdefault(self) -> Any: - owner = 'default' - if self.path in self.temp: - owner = self.temp[self.path]['owner'] - elif self.path in self.model and 'owner' in self.model[self.path]: - owner = self.model[self.path]['owner'] - return owner == 'default' + return self.config.get_owner(self.path) == 'default' class TiramisuOptionValue(_Value): @@ -246,7 +231,7 @@ class TiramisuOptionValue(_Value): self.index = index def get(self) -> Any: - value = self._get_value(self.path, self.schema) + value = self.config.get_value(self.path, self.schema) self._display_warnings(self.path, value, self.schema['type'], self.schema['name']) return value @@ -271,16 +256,18 @@ class TiramisuOptionValue(_Value): self._validate(type_, val) else: self._validate(type_, value) + remote = self.form.get(self.path, {}).get('remote', False) self.config.modify_value(self.path, self.index, value, - self.form.get(self.path, {}).get('remote', False)) + remote) self._display_warnings(self.path, value, type_, self.schema['name']) def reset(self): + remote = self.form.get(self.path, {}).get('remote', False) self.config.delete_value(self.path, self.index, - self.form.get(self.path, {}).get('remote', False)) + remote) class _Option: @@ -288,8 +275,6 @@ class _Option: type='option'): if type not in ['all', 'option']: raise NotImplementedError() - if self.schema.get('properties') is None: - raise Exception(list(self.schema.keys())) for path, schema in self.schema['properties'].items(): if type == 'all' or schema['type'] not in ['object', 'array']: hidden = self.temp.get(path, {}).get('hidden', None) @@ -338,7 +323,8 @@ class TiramisuOptionDescription(_Option): self.model, self.form) if subfunc == 'property': - return TiramisuOptionProperty(self.model.get(self.path, {})) + return TiramisuOptionProperty(self.path, + self.model.get(self.path, {})) if subfunc == 'value': return TiramisuOptionValue(self.config, self.schema, @@ -405,7 +391,8 @@ class TiramisuOption: if subfunc == 'property': if self.index != None: raise NotImplementedError() - return TiramisuOptionProperty(self.model.get(self.path, {})) + return TiramisuOptionProperty(self.path, + self.model.get(self.path, {})) raise APIError(_('please specify a valid sub function ({})').format(subfunc)) @@ -431,10 +418,8 @@ class ContextOption(_Option): self.config = config self.model = model self.form = form - schema = {'properties': schema} - self.schema = schema + self.schema = {'properties': schema} self.temp = temp - self.index = None def __call__(self, path: str, @@ -482,7 +467,6 @@ class ContextValue(_Value): index) def mandatory(self): - # config.value.mandatory() for key, value in self.dict().items(): if self.model.get(key, {}).get('required') and \ value is None or \ @@ -498,7 +482,7 @@ class Config: self.model = {option['key']: option for option in json['model']} self.form = {} for option in json['form']: - if option.get('key'): + if 'key' in option: if 'pattern' in option: option['pattern'] = re.compile(option['pattern']) self.form[option['key']] = option @@ -511,7 +495,6 @@ class Config: else: self.root = '' - def __getattr__(self, subfunc: str) -> Any: if subfunc == 'property': @@ -552,8 +535,9 @@ class Config: new_value = schema.get('defaultvalue') if new_value is None: len_value = len(value) - if len(schema.get('value')) >= len_value: - new_value = schema.get('value')[len_value - 1] + schema_value = schema.get('value', []) + if len(schema_value) >= len_value: + new_value = schema_value[len_value - 1] value[-1] = new_value self.updates_value('modify', @@ -585,6 +569,8 @@ class Config: 'type': 'object'} if root_path: root = self.root.split('.') + if not path.startswith(root): + raise Exception('cannot find {0}'.format(path)) subpaths = path.split('.')[len(root):] else: subpaths = path.split('.') @@ -596,7 +582,33 @@ class Config: schema = schema['properties'][root_path] return schema + def get_hidden(self, + path: str) -> bool: + property_ = 'hidden' + if property_ in self.temp.get(path, {}): + value = self.temp[path][property_] + else: + value = self.model.get(path, {}).get(property_) + return value + def get_value(self, + path: str, + schema: Dict) -> Any: + if 'value' in self.temp.get(path, {}): + value = self.temp[path]['value'] + else: + value = self.model.get(path, {}).get('value') + if value is None and schema.get('isMulti', False): + value = [] + return value + + def get_owner(self, + path: str) -> str: + if 'owner' in self.temp.get(path, {}): + owner = self.temp[path]['owner'] + else: + owner = self.model.get(path, {}).get('owner', 'default') + return owner def updates_value(self, action: str, @@ -609,14 +621,13 @@ class Config: if self.updates: last_body = self.updates[-1] if last_body['name'] == path: - if index is None and not 'index' in last_body: + if index is None and not 'index' in last_body: last_action = last_body['action'] if last_action == action or \ last_action in ['delete', 'modify'] and action in ['delete', 'modify']: update_last_action = True elif index == None and action == 'delete': for update in reversed(self.updates): - update['name'] if masterslaves == None and update['name'] == path or \ masterslaves and path.startswith(masterslaves + '.'): del self.updates[-1] @@ -693,12 +704,12 @@ class Config: def set_dependencies(self, path: str, - value: Any, + ori_value: Any, force_hide: bool=False) -> None: dependencies = self.form.get(path, {}).get('dependencies', {}) if dependencies: - if value in dependencies['expected']: - expected = dependencies['expected'][value] + if ori_value in dependencies['expected']: + expected = dependencies['expected'][ori_value] else: expected = dependencies['default'] for action in ['hide', 'show']: @@ -710,7 +721,7 @@ class Config: hidden = action == 'hide' for expected_path in expected_actions: self.temp.setdefault(expected_path, {})['hidden'] = hidden - if 'value' in self.temp.get(expected_path, {}): + if 'value' in self.temp[expected_path]: value = self.temp[expected_path]['value'] else: value = self.model[expected_path].get('value') @@ -732,11 +743,7 @@ class Config: opts.append(path) for path_ in self.form[path]['not_equal']['options']: schema = self.get_schema(path_) - if not schema.get('isMulti', False): - default_value = None - else: - default_value = [] - p_value = self.model[path_].get('value', default_value) + p_value = self.get_value(path_, schema) if isinstance(p_value, list): for val in p_value: vals.append(val) @@ -745,7 +752,6 @@ class Config: vals.append(p_value) opts.append(path_) equal = [] - is_current = False warnings_only = self.form[path]['not_equal'].get('warnings', False) if warnings_only: msg = _('should be different from the value of "{}"') @@ -757,8 +763,6 @@ class Config: for idx_sup, val_sup in enumerate(vals[idx_inf + 1:]): if val_inf == val_sup is not None: for opt_ in [opts[idx_inf], opts[idx_inf + idx_sup + 1]]: - if opt_ == path: - is_current = True if opt_ not in equal: equal.append(opt_) if equal: @@ -766,7 +770,6 @@ class Config: for opt in equal: schema = self.get_schema(opt) equal_name[opt] = schema['title'] - len_equal_name = len(equal) for opt_ in equal: display_equal = [] for opt__ in equal: @@ -794,10 +797,9 @@ class Config: copy = self.form.get(path, {}).get('copy') if copy: for opt in copy: - owner = self.temp.get(opt, {}).get('owner') - if owner is None: - owner = self.model[opt]['owner'] + owner = self.get_owner(opt) if owner == 'default': + # do not change in this.temp, it's default value self.model[opt]['value'] = value def send_data(self,