def _parse_validators(self, value): """ Parse validators string and try to convert it to list with actual validator functions. """ if not value: return [] items = map(lambda item: item.strip(), value.split(',')) validators = [] for item in items: try: validator = load_from_path(item) except (AttributeError, ImportError): logger.exception('Cannot load %r validator for %s setting.', item, self.name) continue validators.append(validator) return validators
def _parse_choices(self, value): """ Convert string value to valid choices tuple. **Supported formats:** * a, b, c * (a, A), (b, B), (c, C) * a { b, c }, d { e, f } * A { (b, B), (c, C) }, D { (e, E), (f, F) } * path.to.CHOICES * path.to.Model.CHOICES """ # Start parsing with internal choices if not ',' in value and '.' in value: # Choices tuple should be last part of value path, attr = value.rsplit('.', 1) # Load choices from module try: module = importlib.import_module(path) except ImportError: # Or from module class try: module = load_from_path(path) except (AttributeError, ImportError): logger.exception('Cannot load choices from %r path', value) return () # Try to get choices attr in module try: choices = getattr(module, attr) except AttributeError: logger.exception('Cannot load choices from %r path', value) return () elif not '{' in value and not '}' in value: # Parse choice with labels label_re = re.compile(r'\(([^,]+),\s+([^\)]+)\)', re.M) found = label_re.findall(value) if found: choices = found # If nothing found by regex, just split value by comma and # duplicate resulted items else: choices = map(lambda item: (item.strip(), item.strip()), value.split(',')) else: # Parse groups groups_re = re.compile(r'([^{]+){([^}]+)},?', re.M) found = groups_re.findall(value) if found: choices = [] for group, data in found: group = group.strip() choices.append((group, self._parse_choices(data.strip()))) else: logger.error('Cannot parse choices from %r', value) return () return tuple(choices)