如何将 **kwargs 作为参数传递给 FastAPI 端点?

发布于 2025-01-16 11:54:10 字数 1017 浏览 3 评论 0原文

我有一个生成 dict 模板的函数。该函数由多个生成器组成,需要一个参数(即 Carrier),并具有许多可选参数(关键字参数 - **kwargs)。

def main_builder(carrier, **params):
    output = SamplerBuilder(DEFAULT_JSON)
    output.generate_flight(carrier)
    output.generate_airline_info(carrier)
    output.generate_locations()
    output.generate_passengers()
    output.generate_contact_info()
    output.generate_payment_card_info()
    output.configs(**params)
    result = output.input_json
    return result 

# example of function call
examplex = main_builder("3M", proxy="5.39.69.171:8888", card=Visa, passengers={"ADT":2, "CHD":1}, bags=2)

我想将此功能部署到 FastAPI 端点。我设法为 Carrier 做到这一点,但如何将 **kwargs 设置为函数的参数?

@app.get("/carrier/{carrier_code}", response_class=PrettyJSONResponse) # params/kwargs??
async def get_carrier(carrier_code):
    output_json = main_builder(carrier_code)
    return airline_input_json

I have a function generating a dict template. This function consists of several generators and requires one parameter (i.e., carrier) and has many optional parameters (keyword arguments - **kwargs).

def main_builder(carrier, **params):
    output = SamplerBuilder(DEFAULT_JSON)
    output.generate_flight(carrier)
    output.generate_airline_info(carrier)
    output.generate_locations()
    output.generate_passengers()
    output.generate_contact_info()
    output.generate_payment_card_info()
    output.configs(**params)
    result = output.input_json
    return result 

# example of function call
examplex = main_builder("3M", proxy="5.39.69.171:8888", card=Visa, passengers={"ADT":2, "CHD":1}, bags=2)

I want to deploy this function to FastAPI endpoint. I managed to do it for carrier but how can I set **kwargs as params to the function?

@app.get("/carrier/{carrier_code}", response_class=PrettyJSONResponse) # params/kwargs??
async def get_carrier(carrier_code):
    output_json = main_builder(carrier_code)
    return airline_input_json

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2025-01-23 11:54:10

使用 Pydantic 模型

由于您的函数“..有许多可选参数”passengers 参数需要字典作为输入,我建议创建一个 Pydantic 模型,在其中定义参数,这将允许您以 JSON 格式发送数据并让 Pydantci 自动验证它们。调用端点后,您可以使用 Pydantic 的 dict() 方法(注意:在 Pydantic V2 中,dict()model_dump() 取代——参见 此答案了解更多详细信息)将模型转换为字典。

示例

from pydantic import BaseModel
from typing import Optional

class MyModel(BaseModel):
    proxy: Optional[str] = None
    card: Optional[str] = None
    passengers: Optional[dict] = None 
    bags: Optional[int] = None

@app.post("/carrier/{carrier_code}")
async def get_carrier(carrier_code: int, m: MyModel):
    return main_builder(carrier_code, **m.dict())  # In Pydantic V2, use **m.model_dump()

发送任意 JSON 数据的

如果您必须发送任意 JSON 数据,因此无法预先定义端点的参数,您可以使用类似于中描述的方法此答案(请参阅选项 3 和 4),以及这个答案这个答案

Using Pydantic Model

Since your function "..has many optional parameters" and passengers parameter requires a dictionary as an input, I would suggest creating a Pydantic model, where you define the parameters, and which would allow you sending the data in JSON format and getting them automatically validated by Pydantci as well. Once the endpoint is called, you can use Pydantic's dict() method (Note: In Pydantic V2, dict() was replaced by model_dump()—see this answer for more details) to convert the model into a dictionary.

Example

from pydantic import BaseModel
from typing import Optional

class MyModel(BaseModel):
    proxy: Optional[str] = None
    card: Optional[str] = None
    passengers: Optional[dict] = None 
    bags: Optional[int] = None

@app.post("/carrier/{carrier_code}")
async def get_carrier(carrier_code: int, m: MyModel):
    return main_builder(carrier_code, **m.dict())  # In Pydantic V2, use **m.model_dump()

Sending arbitrary JSON data

In case you had to send arbitrary JSON data, and hence, pre-defining the parameters of an endpoint wouldn't be possible, you could use an approach similar to the one described in this answer (see Options 3 and 4), as well as this answer and this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文