Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pydantic Model Validation Error for Missing Field #2

Closed
Lucian-Williamson opened this issue Dec 1, 2023 · 1 comment
Closed

Pydantic Model Validation Error for Missing Field #2

Lucian-Williamson opened this issue Dec 1, 2023 · 1 comment

Comments

@Lucian-Williamson
Copy link

When attempting to instantiate an instance of the Pydantic model BRDP using the deprecated parse_raw method, a validation error occurs when a dictionary object lacks a required field, specifically the event field. Despite event being defined as optional within the BRDP model, the parsing process expects this field to be present within the provided dictionary, causing a validation error.

The absence of the event field within the dictionary passed to parse_raw results in a validation error, although event is marked as optional within the BRDP model.

This issue affects processes that rely on parsing dictionaries into Pydantic models using the deprecated parse_raw method, causing unexpected validation errors when optional fields are missing.

from pydantic import BaseModel
from typing import Optional, Dict, Any
import json

class BRDP(BaseModel):
    """BRDP of YoLink API."""
    code: str
    desc: str
    method: str
    data: Dict[str, Any]
    event: Optional[str]  # 'event' field is marked as optional


# Sample JSON data missing the 'event' field
json_string = '''
{
    "code": "000000",
    "time": 1701414599470,
    "msgid": 1701414599470,
    "method": "Home.getGeneralInfo",
    "desc": "Success",
    "data": {"id": "53c5283d408d4e6aba799330fbeeeaa9"}
}
'''

# Attempt to create a BRDP object using the provided JSON data
try:
    brdp = BRDP()
    brdp.parse_raw(json_string)
    print(brdp)
except Exception as e:
    print(f"Validation error occurred: {e}")

"""
Error:
event
  Field required [type=missing, input_value={}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.5/v/missing
""""

This is fixed by using:

    brdp = BRDP.model_construct(**json.loads(json_string))

Need perms to open a PR.

@matrixd2
Copy link
Collaborator

matrixd2 commented Dec 6, 2023

Thank you, Since this repository is for providing YoLink device support to HomeAssistant and many other integrations in HomeAssistant also use the Pydantic library, HomeAssistant will not update the Pydantic library to the V2 version in the short term.

@matrixd2 matrixd2 closed this as completed Apr 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants