Code: Select all
from .consts import BASE_URL, HOSTNAME_PATTERN
class GenericParseException(Exception):
pass
def validate_hostname(value: str) -> str:
if value.startswith("http://") or value.startswith("https://"):
raise GenericParseException("base_url should not include the protocol (http:// or https://)")
if not re.match(HOSTNAME_PATTERN, value):
raise GenericParseException("Invalid hostname format.")
return value
HostnameType = Annotated[str, AfterValidator(validate_hostname)]
class Config(BaseModel):
api_token: str
base_url: HostnameType = BASE_URL
class ConfigParser:
def __init__(self, logger: LoggerInterface):
self.logger = logger
def parse(self, config: dict[str, Any]) -> Config:
errors: List[str] = []
try:
model = Config(**config)
return model
except ValidationError as e:
errors.extend(e.errors())
except GenericParseException as e:
errors.append(f"Generic validation error: {e}")
except Exception as e:
errors.append(f"Unexpected error: {e}")
finally:
if errors:
self.logger.error({
'action': 'validation',
'status': 'failed',
'errors': errors
})
raise ConfigParseException("; ".join(str(err) for err in errors))
Ich habe es sowohl mit AfterValidator als auch mit BeforeValidator
Die erwartete Ausgabe sollte etwa so aussehen:
Code: Select all
api_token - required field
base_url - base_url should not include the protocol (http:// or https://)
Irgendwelche Ideen?