Part1 问题抛出
前面我们已经了解了查询参数,但是实际开发中我们可能需要限定参数的类型,长度等其他属性。这个时候我们就需要对查询参数进行校验。
类型我们可以通过显示类型进行限制,但是长度等其他属性我们需要借助 FastApi 的 Query 对象来实现。
Part2 实例
实现方式
参数限定,我们需要借助 fastapi 中的 Query 对象来实现。
导入 Query
from fastapi import Query
复制代码
限定参数最大长度
使用参数:max_length
@app.get('/len')async def get_len(q:str=Query(...,max_length=2)): res = {'name':'phyger'} if q: res.update({'q':q}) return res
复制代码
从以上测试可知:
查询参数 q 为可选参数、最大长度为 2,超过最大长度 fastapi 将会报错。
限定参数最小长度
使用参数:min_length
@app.get('/len')async def get_len(q:Optional[str]=Query(None,min_length=2,max_length=5)): res = {'name':'phyger'} if q: res.update({'q':q}) return res
复制代码
Query 类型的查询参数必须制定默认值。形如:Query(...,min_length=2,max_length=5)
除了限定长度,我们还可以通过 regex 属性来通过正则表达式限定参数格式
默认查询参数
可选查询参数: 通常我们使用 Optional 类型结合 Query 类型的默认值来实现;
async def get_len(q:Optional[str]=Query(None,min_length=2,max_length=5)): pass
复制代码
async def get_len(q:str=Query(None,min_length=2,max_length=5)): pass
复制代码
以上两种方式都可。
必选查询参数: 通常我们指定 Query 的默认值为...来实现。
async def get_len(q:str=Query(...,min_length=2,max_length=5)): pass
复制代码
当 Optional 类型和...默认参数同时存在的时候,查询参数依然为必选。
多个查询参数
当我们需要设计多个查询参数的时候,我们可以这样写。
from typing import Listfrom fastapi import Query@app.get('/len')async def get_len(q:Optional[List[str]]=Query(...,min_length=2,max_length=5)): res = {'name':'phyger'} if q: res.update({'q':q}) return res
复制代码
直接使用 list 也可以
from typing import Listfrom fastapi import Query@app.get('/len')async def get_len(q:Optional[list]=Query(...)): res = {'name':'phyger'} if q: res.update({'q':q}) return res
复制代码
Part3 更多的元数据
title
Query 的 title 属性可以让我们指定参数的标题,用做提示。
from fastapi import Query@app.get('/title/')async def title(name:str = Query(...,title="test title",max_length=5,min_length=2)): return {'result':name}
复制代码
description
from fastapi import Query@app.get('/title/')async def title(name:str = Query(...,title="test title",max_length=5,min_length=2,description='test desc')): return {'result':name}
复制代码
doc 中的效果
别名
实际应用中,有时候查询参数可能形如 x-name,这在 python 中不是合法的变量,为了解决类似问题,FastApi 为我们提供了别名 alias 功能。
from fastapi import Query@app.get('/title/')async def title(name:str = Query(...,max_length=5,min_length=2,alias='x-name')): return {'result':name}
复制代码
参数弃用
当我们计划在后续版本中废弃参数时,我们可以通过 deprecated 属性来提示用户。
from fastapi import Query@app.get('/title/')async def title(name:str = Query(...,max_length=5,min_length=2,alias='x-name',deprecated=True)): return {'result':name}
复制代码
接口文档中的效果
评论