Skip to content

[Feature Request] Parameter validation optimization #277

@jsonvot

Description

@jsonvot

Is your feature request related to a problem? Please describe your use case.
When using validate to verify request parameters, there are certain scenarios that cannot be covered, resulting in insufficient rigor of the functionality. For example:

# sanic_ext\extras\validation\clean.py

# before
def clean_data(model: type[object], data: dict[str, Any]) -> dict[str, Any]:
    hints = get_type_hints(model)
    return {key: _coerce(hints[key], value) for key, value in data.items()}
# after
# Can avoid the throwing of KeyError.
def clean_data(model: type[object], data: dict[str, Any]) -> dict[str, Any]:
    hints = get_type_hints(model)
    hints_keys = set(hints.keys())
    return {key: _coerce(hints[key], value) for key, value in data.items() if key in hints_keys}

# sanic_ext\extras\validation\clean.py

# before
def _coerce(param_type, value: Any) -> Any:
    if (
        get_origin(param_type) is not list
        and isinstance(value, list)
        and len(value) == 1
    ):
        value = value[0]

    return value

# after
# In Pydantic, list-type data can be represented in multiple ways.
# e.g. list or list[str] or List[str]
def _coerce(param_type, value: Any) -> Any:
    if param_type is list and isinstance(value, list):
        return value
    if (
            get_origin(param_type) is not list
            and isinstance(value, list)
            and len(value) == 1
    ):
        return value[0]
    return value

Describe the solution you'd like
A clear and concise description of what you want to happen.

Additional context
Add any other context about the feature request here. This might be which part of source code to modify or some information you think it might help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions