如何配置 openapi-generator-cli 以在 Pydantic 模型中包含可为空字段的 None 值

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

我正在使用 openapi-generator-cli 生成 Python 客户端,除了特定场景外,它运行良好。我需要将请求发送到外部服务,其中必须包含所有可为空的字段,即使它们的值为“无”。当我使用 openapi-generator-cli 生成客户端时,它会使用 to_dict 方法创建模型,如下所示:

def to_dict(self) -> Dict[str, Any]:
    """Return the dictionary representation of the model using alias.

    This has the following differences from calling pydantic's
    `self.model_dump(by_alias=True)`:

    * `None` is only added to the output dict for nullable fields that
      were set at model initialization. Other fields with value `None`
      are ignored.
    """
    excluded_fields: Set[str] = set([
    ])

    _dict = self.model_dump(
        by_alias=True,
        exclude=excluded_fields,
        exclude_none=True,
    )

有没有办法配置 openapi-generator-cli 以允许在 to_dict 方法中包含可为空字段的 None 值?如果

exclude_none=False
这将完成,但我没有找到任何用于 openapi-generator 的指令。

假设我有一个像这样的Python字典:

request_data = {
    "account": None,
    "lastName": "Doe",
    "firstName": "Jon",
    "middleInitial": None,
    "companyName": None,
    "isOrganization": False,
    "address": {
        "type": "P",
        "address1": "5171 California Avenue",
        "address2": "Suite 200",
        "address3": None,
        "address4": None,
        "locality": "Irvine",
        "region": "CA",
        "postalCode": "92617",
        "countryCode": "US"
    }
}

在此示例中,即使“account”、“middleInitial”和“companyName”等某些字段为 None,我也需要将它们包含在发送到外部服务的请求中。

补充说明:

也许问题不在于 openapi-generator 的配置,而在于用于创建这些模型的 Swagger 文件。但是,我在 Swagger 文件中找不到任何可生成所需模型的配置。这是我的 Swagger 模型的片段:

User:
  type: object
  required:
    - address
  properties:
    account:
      type: string
      default: null 
    middleInitial:
      type: string
      default: null 
    lastName: 
      type: string
      default: null 
    firstName: 
      type: string
      default: null 
    companyName:
      type: string
      default: null 
    isOrganization: 
      type: boolean
      default: null 
    address: 
      $ref: "#/components/schemas/Adress"
python swagger pydantic openapi-generator openapi-generator-cli
1个回答
0
投票

我在这个问题上找到了解决方案。我使用了 Mustache 模板来覆盖 docker cli 上的相同模板。

docker run --rm \
    -v ${PWD}:/local openapitools/openapi-generator-cli:latest-release generate \
    --input-spec https://api.swaggerhub.com/apis/supercoolapi/$API_VERSION?resolved=true \
    --auth "Authorization: ${SWAGGER_API_TOKEN}" \
    --generator-name python \
    --output /local \
    --additional-properties=packageVersion=$PACKAGE_VERSION,packageName=$PACKAGE_NAME,library=asyncio \
    --template-dir /local/templates

我使用了这个模板并重写了如何创建 to_dict 方法。

© www.soinside.com 2019 - 2024. All rights reserved.