英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论