Search code examples
pythonpydantic

Python error making structure "Field required"


I'm trying to add Account to Settings and I get the following error. This doesn't make any sense because I pass in both user and pass, so why does it say I'm missing a field. If I remove the accounts var from settings the error goes away.

 Field required [type=missing, input_value={'user': '3EE590j6dB', 'pass_': 'PaDPzEIBjF'}, input_type=dict]
   For further information visit https://errors.pydantic.dev/2.8/v/missing
from py3xui.client.client import Client
from py3xui.inbound.bases import JsonStringModel
from pydantic import BaseModel, Field
from typing import List, Optional

# pylint: disable=too-few-public-methods
class SettingsFields:
    """Stores the fields returned by the XUI API for parsing."""

    CLIENTS = "clients"
    DECRYPTION = "decryption"
    FALLBACKS = "fallbacks"

# Define the Account class
class Account(BaseModel):
    user: str
    pass_: str = Field(alias='pass')  # Using alias because 'pass' is a reserved keyword

# Define the Settings class
class Settings(JsonStringModel):
    accounts: List[Account] = []
    clients: Optional[List[Client]] = None
    decryption: Optional[str] = None
    fallbacks: Optional[List] = None
# ERROR HERE ---
def add_inbounds(startingPort, count):
       settings = Settings(
           accounts=[
               Account(user="hello", pass_="hello")
           ]
       )

Solution

  • The constructor of Account model expects pass parameter, not pass_.

    You can solve this problem in at least two ways:

    1. use Account.model_validate() and pass arguments as a dict:
    settings = Settings(
               accounts=[
                   Account.model_validate({"user": "hello", "pass": "hello"})
               ]
           )
    
    1. define multiple validation aliases using AliasChoices
        pass_: str = Field(
            serialization_alias="pass", validation_alias=AliasChoices('pass', 'pass_')
        )