fastapi(五)查询参数字符串认证

fastapi 允许为你的参数添加附加的信息和验证
eg:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = None):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

附加验证
我们将在q参数上添加强制验证,无论是否提供该参数,它将最长拥有50个字符

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = Query(None, max_length=50)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results

使用Query作为默认值
现在使用query作为默认参数值,并设置max_length为50

async def read_items(q: str = Query(None, max_length=50)):

其中第一个参数为定义的默认值。
这种方式定义将明显的声明它为查询参数。

添加更多的验证

async def read_items(q: str = Query(None, min_length=3, max_length=50)):

添加正则表达式
同时也可定义一个正则表达式来匹配参数。

async def read_items(
q: str = Query(None, min_length=3, max_length=50, regex="^fixedquery$")
):

^表示以什么为开头,
$表示以什么为结尾

使其required
在之前的章节中当参数声明中没有默认值得时候,它就是必须的,
q:str
所以当使用Query来声明查询参数时可以使用…作为第一个参数,来表示必须。

async def read_items(q: str = Query(…, min_length=3)):

符号“…”他是特殊的值,在python中被称为“Ellipsis”

Query参数使用list或多个值
当使用Query来定义查询参数时可以声明为接收一个list,来表示接收多个值

from typing import List

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: List[str] = Query(None)):
    query_items = {"q": q}
    return query_items

然后URL就可以这样写:

http://localhost:8000/items/?q=foo&q=bar

直接使用list

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: list = Query(None)):
    query_items = {"q": q}
    return query_items

在这个例子中fastapi将不会验证这个list中的值,

添加更多的metadata

添加的这些metadata将自动添加到openapi中,以及docs文档中和其他工具。

添加title以及description

@app.get("/items/")
async def read_items(
q: str = Query(
None,
title=“Query string”,
description=“Query string for the items to search in the database that have a good match”,
min_length=3,
)
):

别名参数
如果你想在参数中使用像item-query这样的参数,但是它并不是一个可用的python变量名。
然后就可以使用alias,它将被用于查找参数值:

@app.get("/items/")
async def read_items(q: str = Query(None, alias=“item-query”)):

deprecating 参数
当你不想再使用某个参数的时候,但是又必须保留这个参数(因为有客户端在使用)但是你想在docs中显示为deprecated,可以在Query中设置deprecated=True

@app.get("/items/")
async def read_items(
q: str = Query(
None,
alias=“item-query”,
title=“Query string”,
description=“Query string for the items to search in the database that have a good match”,
min_length=3,
max_length=50,
regex="^fixedquery$",
deprecated=True,
)
):

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值