Python 错误使结构“需要字段”

问题描述 投票:0回答:1

我尝试将帐户添加到“设置”,但收到以下错误。这没有任何意义,因为我同时传入了 user 和 pass,那么为什么它说我缺少一个字段。如果我从设置中删除

accounts
var,错误就会消失。

 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")
           ]
       )
python pydantic
1个回答
0
投票

Account
模型的构造函数需要
pass
参数,而不是
pass_

您至少可以通过两种方式解决这个问题:

  1. 使用
    Account.model_validate()
    并将参数作为字典传递:
settings = Settings(
           accounts=[
               Account.model_validate({"user": "hello", "pass": "hello"})
           ]
       )
  1. 使用
    AliasChoices
  2. 定义多个验证别名
    pass_: str = Field(serialization_alias="pass", validation_alias=AliasChoices('pass', 'pass_'), )
© www.soinside.com 2019 - 2024. All rights reserved.