前言:
在fastapi中,我们定义的查询参数是可以设置成:必选参数 or 可选参数。
可选查询参数 只要给查询参数的默认值设置为 None ,表示该查询参数是可选参数。
?from fastapi import FastAPI
??
?app = FastAPI()?
?@app.get("/items/{item_id}")
?async def read_item(item_id: str, q=None):
? ? ?data = {"item_id": item_id}
? ? ?if q:
? ? ? ? ?data["q"] = q
? ? ?return data
补充: 此时路径操作函数内的参数有两个,一个是路径参数 item_id ,一个是查询参数 q ,fastapi是可以区分他们的。
必选查询参数 当你为查询参数设置默认值时,则该参数在URL中不是必须的。 如果你不想添加默认值,而只是想使该参数成为可选的,则将默认值设置为 None 。 但当你想让一个查询参数成为必需的,不声明任何默认值就可以. 比如:这里的查询参数 needy 是类型为 str 的必需查询参数。
?from fastapi import FastAPI ?? ?app = FastAPI()? ?@app.get("/items/{item_id}") ?async def read_user_item(item_id: str, needy: str): ? ? ?item = {"item_id": item_id, "needy": needy} ? ? ?return item如果在URL中没有查询参数 needy ,则报错?{ ? ? "detail": [ ? ? ? ? { ? ? ? ? ? ? "loc": [ ? ? ? ? ? ? ? ? "query", ? ? ? ? ? ? ? ? "needy" ? ? ? ? ? ? ], ? ? ? ? ? ? "msg": "field required", ? ? ? ? ? ? "type": "value_error.missing" ? ? ? ? } ? ? ] ?}
可选和必选参数共存 也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的 此时: itme_id 是路径参数, needy 是必选路径参数, skip 是有默认值必选查询参数, limit 是可选查询参数。
?from fastapi import FastAPI ?? ?app = FastAPI() ?@app.get("/items/{item_id}") ?async def read_user_item( ? ? ?item_id: str, needy: str, skip: int = 0, limit=None ?): ? ? ?item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit} ? ? ?return item
为可选参数做类型提示 比如一个可选的参数 q ,如有该参数时,他的类型是整型,此时定义类型提示如下 使用 typing 模块下的 Union 做类型提示, Union[int, None] 表示类型是 int 或者 None 此时对于URL: http://127.0.0.1:8000/items/12?q=12 ,参数 q 就会自动转化为数字12
?from typing import Union? ?from fastapi import FastAPI ?app = FastAPI()? ?@app.get("/items/{item_id}") ?async def read_item(item_id: str, q: Union[int, None] = None): ? ? ?data = {"item_id": item_id} ? ? ?if q: ? ? ? ? ?data["q"] = q ? ? ?return data补充1:
可能为空的情况做类型提示,一般使用一个比 typing.Union 更加方便的类型: typing.Optional 因为, Optional[X] is equivalent to Union[X, None] 所以,上面的类似等价于 q: Optional[int] = None \补充2:
只要给查询参数默认值 None 就表示它是可选查询参数,和类型提示无关。 类型提示的功能在于如果该值存在是他应该是什么类型的变量并做类型转换和校验。到此这篇关于python中fastapi设置查询参数可选或必选的文章就介绍到这了,更多相关python fastapi 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于python中fastapi设置查询参数可选或必选的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did16790