unioslo / harborapi

Python async client for the Harbor REST API v2.0.
https://unioslo.github.io/harborapi/
MIT License
28 stars 6 forks source link

Ability to disable validation #22

Closed pederhan closed 1 year ago

pederhan commented 1 year ago

In cases where the models don't match the API output - be it due to errors in the spec or in harborapi itself, we should have a way to disable validation when instantiating models. Adding this switch would also have the benefit of adding a performance increase in cases where the data is trusted and validation is not necessary.

Validation should be enabled by default (as it is today), but an attribute on the client itself should be exposed to let users control it.

Changing construct_model

construct_model() today assumes we want to validate the data:

https://github.com/pederhan/harborapi/blob/e06b6cd8933807348fd933c8d85b47fac547c114/harborapi/client.py#L97-L102

By adding a switch to the client, we can then pass an argument to a new validate parameter on construct_model() that changes the model construction strategy based on the argument:

def construct_model(cls: Type[T], data: Any, validate: bool = True) -> T:
    try:
        if validate:
            return cls.parse_obj(data)
        else:
            return cls.construct(**data)
    except ValidationError as e:
        logger.error("Failed to construct {} with {}", cls, data)
        raise e

Return raw results

Another attribute we could add is raw, wherein the results aren't even passed to Pydantic; we simply return the data as-is. This, of course, breaks all promises of type safety, and should be treated as "unsafe". Open a separate issue for this if this functionality is desired.

pederhan commented 1 year ago

Do note that using construct() will prevent any nested models from being instantiated, but that's fine if our goal is to just allow users to brute force the retrieval of data from the API.