如何在由FastAPI生成的API规范中生成Long类型变量?

huangapple go评论91阅读模式
英文:

How to generate Long type variable in API spec generated by FastAPI?

问题

这个类是一个项目的一部分:

from pydantic import BaseModel, StrictInt, constr, validator


class Person(BaseModel):
    person_id: StrictInt
    person_name: constr(strip_whitespace=True, strict=True)

    @validator('person_id')
    def person_id_validator(cls, val):
        assert val is not None
        return val

    @validator('person_name')
    def person_name_validator(cls, val):
        assert val != ''
        return val

当使用 FastAPI().openapi() 为这个类生成 API 规范时,变量 person_id 的类型始终是 integer,因此从该规范生成的 Java 客户端始终对变量 personId 使用包装类 Integer。然而,personId 可能是一个非常长的数字(> 5,000,000,000),我无法将其保留在 Integer 中。

Pydantic 本身没有内置的 Long。Python 在内部处理 int32 和 int64,所以我也无法控制这一点。我尝试使用 class Config 中的 arbitrary_types_allowed,结合 numpy.int64torch.long,但在运行时始终会出现以下消息:

ValueError: Value not declarable with JSON Schema, field: name='person_id' type=int64 required=True

我该如何实现这一点?

英文:

This class is a part of a project:

from pydantic import BaseModel, StrictInt, constr, validator


class Person(BaseModel):
    person_id: StrictInt
    person_name: constr(strip_whitespace=True, strict=True)

    @validator('person_id')
    def person_id_validator(cls, val):
        assert val is not None
        return val

    @validator('person_name')
    def person_name_validator(cls, val):
        assert val != ''
        return val

When the API-spec is generated for this class using FastAPI().openapi(), the type of the variable person_id is always integer and consequently, the Java client generated from that spec always has the wrapper class Integer for the variable personId. However, personId can be a very long number (>5,000,000,000) which I can't keep in an Integer.

Pydantic itself doesn't have a Long built-in. Python handles int32 and int64 internally so I cannot control that either. I tried using numpy.int64 and torch.long with the help of arbitrary_types_allowed in class Config but that always fails at runtime with the message
ValueError: Value not declarable with JSON Schema, field: name='person_id' type=int64 required=True.

How do I achieve this?

答案1

得分: 2

在OpenAPI中,长整数被定义为:

type: integer
format: int64

关键在于使用正确的 format。在使用FastAPI/Pydantic时,您可以如下添加 format 属性:

person_id: StrictInt = Field(..., format='int64')
英文:

In OpenAPI, long integers are defined as:

type: integer
format: int64

The key is to use the proper format. When using FastAPI/Pydantic, you can add the format attribute as follows:

person_id: StrictInt = Field(..., format='int64')

huangapple
  • 本文由 发表于 2023年7月10日 21:11:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定