在FastAPI中验证小数位数

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

Validate number of decimal places in FastAPI

问题

使用FastAPI(以及pydantic),是否有内置的方式来验证查询参数的小数位数?

例如,我想要允许仅接受美元货币值,因此只允许有2位小数。例如,12.34将被允许,但12.345将不被允许,因为它有3位小数。

以下是我的当前代码:

@app.post("send_usd")
async def send_usd(amount: Decimal = Query(gt=0)):
    pass

是否有内置的方式(不需要编写自定义验证器或正则表达式),类似于以下示例:

amount: Decimal = Query(gt=0, decimal_places=2)
英文:

Using FastAPI (and pydantic), is there a built-in way to validate the number of decimal places of a query parameter?

For example, I want to allow monetary values in USD only, such that only 2 decimal places are allowed. For example, 12.34 would be allowed, but 12.345 would not as it has 3 decimal places.

Here is my current code:

@app.post("send_usd")
async def send_usd(amount: Decimal = Query(gt=0)):
    pass

Is there a built-in way (without writing a custom validator or regex) similar to the following example:

amount: Decimal = Query(gt=0, decimal_places=2)

答案1

得分: 1

amount 需要通过查询字符串传递吗?如果可以使用请求主体而不是查询字符串,这可能是一个选项:

from typing import Optional
from pydantic import BaseModel, Field
from decimal import Decimal

class MyData(BaseModel):
    amount: Optional[Decimal] = Field(ge=0.01, decimal_places=2)

@app.post("send_usd")
async def send_usd(data: MyData):
    pass
英文:

Does the amount need to be passed via querystring? If you can use the body instead, this could be an option:

from typing import Optional
from pydantic import BaseModel, Field
from decimal import Decimal

class MyData(BaseModel):
    amount: Optional[Decimal] = Field(ge=0.01, decimal_places=2)

@app.post("send_usd")
async def send_usd(data: MyData):
    pass

huangapple
  • 本文由 发表于 2023年6月2日 11:11:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386905.html
匿名

发表评论

匿名网友

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

确定