如何将 **kwargs 作为参数传递给 fastAPI 函数

How to pass **kwargs as params to fastAPI function

我有生成字典模板的功能。函数由多个生成器组成,需要一个参数 - 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

因为你的函数 ".. 有很多可选参数"passengers 参数需要一个字典作为输入,我建议你创建一个 Pydantic 模型,其中您定义参数,它允许以 JSON 形式发送数据并验证它们,以及使用 dict() 方法将模型转换为字典。

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())