从pydantic模型查询参数 [英] Query parameters from pydantic model

查看:66
本文介绍了从pydantic模型查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将pydantic模型转换为fastapi中的查询参数?

Is there a way to convert a pydantic model to query parameters in fastapi?

我的某些端点通过主体传递参数,但其他一些端点直接在查询中传递参数.所有这些端点共享相同的数据模型,例如:

Some of my endpoints pass parameters via the body, but some others pass them directly in the query. All this endpoints share the same data model, for example:

class Model(BaseModel):
    x: str
    y: str

我想避免在查询参数端点"的定义中重复该模型的定义,例如此代码中的 test_query :

I would like to avoid duplicating my definition of this model in the definition of my "query-parameters endpoints", like for example test_query in this code:

class Model(BaseModel):
    x: str
    y: str

@app.post("/test-body")
def test_body(model: Model): pass

@app.post("/test-query-params")
def test_query(x: str, y: str): pass

最干净的方法是什么?

推荐答案

文档给出了快捷方式以避免这种重复.在这种情况下,它将给出:

The documentation gives a shortcut to avoid this kind of repetitions. In this case, it would give:

from fastapi import Depends

@app.post("/test-query-params")
def test_query(model: Model = Depends()): pass

这将允许您请求/test-query-params?x = 1& y = 2 ,并且还将为此端点生成正确的OpenAPI描述.

This will allow you to request /test-query-params?x=1&y=2 and will also produce the correct OpenAPI description for this endpoint.

类似的解决方案可用于将Pydantic模型用作表单数据描述符.

Similar solutions can be used for using Pydantic models as form-data descriptors.

这篇关于从pydantic模型查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆