简体   繁体   English

"FastAPI\/Pydantic 可以单独验证列表中的输入项吗?"

[英]Can FastAPI/Pydantic individually validate input items in a list?

I have a FastAPI post method:我有一个 FastAPI 发布方法:

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from typing import List

import pandas as pd

class InputItem(BaseModel):
    Feature: str

class Item(BaseModel):
    Feature: str
    Result: str

app = FastAPI()

@app.post("/", response_model=List[OutputItem])
def my_function(input: List[InputItem]): 
    df = pd.DataFrame(jsonable_encoder(input))
    result = df.apply(another_method)
    return result.to_dict(orient=records)

My question is, if I pass it a list like this:我的问题是,如果我将它传递给这样的列表:

[
  {"NOTFeature":"value"},
  {"Feature":"value"},
  {"Feature":"value"}
]

or if one of the values is of a different data type, the whole thing currently fails and returns an error.或者如果其中一个值属于不同的数据类型,则整个事情当前失败并返回错误。 Is there a way to get it to handle the error so that the failing entry is skipped, and the API function is still carried out for items in the list which do pass validation?有没有办法让它处理错误,以便跳过失败的条目,并且仍然对列表中通过验证的项目执行 API 函数?

Incidentally, if there's a smoother way to handle the dataframe conversion which still uses the dataframe (these are essential for the other data handling done in the functions), this would be very helpful to know as well!顺便说一句,如果有一种更流畅的方法来处理仍然使用数据帧的数据帧转换(这些对于函数中完成的其他数据处理是必不可少的),这也将非常有帮助!

welcome to Stack Overflow.欢迎使用堆栈溢出。

The short answer for your question is no .您的问题的简短答案是否定的 That's because it's not pydantic (and also FastAPI ) responsability to handle payload contents or fix malformed payloads.那是因为处理有效负载内容或修复格式错误的有效负载不是pydantic (以及FastAPI )的责任。

The right way you could do that is to make the Feature member Optional and filter out when it gets to your method, something like this:您可以这样做的正确方法是使Feature成员成为Optional并在它到达您的方法时过滤掉,如下所示:

import fastapi
import typing
import pydantic

class InputItem(pydantic.BaseModel):
    feature: typing.Optional[str]

class OutputItem(pydantic.BaseModel):
    Feature: str
    Result: str

app = fastapi.FastAPI()

@app.post("/", response_model=typing.List[OutputItem])
def my_function(data: typing.List[InputItem]):
    data = [i for i in data if i.feature is not None]
    print(data)
    # ... do what you gotta do

Union with dict as a passthrough seemed to work for me, ie:与 dict 联合作为传递似乎对我有用,即:

from typing import List, Union

@app.post("/", response_model=List[OutputItem])
def my_function(input: List[Union[InputItem, dict]]): 
    df = pd.DataFrame(jsonable_encoder(input))
    result = df.apply(another_method)
    return result.to_dict(orient=records)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM