FastAPI官档精编007 - 路径参数

Python大咖谈

共 4284字,需浏览 9分钟

 · 2021-10-03

呆鸟云:发布本系列旨在推广 FastAPI 以及推进 FastAPI 中文官档翻译,目前,已完成 98% 的中文官档翻译,如果您对 FastAPI 有兴趣,可以为这个很赞的开源项目做些贡献,比如校译、翻译、审阅等。

开源项目的发展离不开大家的支持。当然最简单的就是在 Github 上点 Star 了。

如果觉得 FastAPI 不错,您也可以转发、转载本文,让更多人知道 Python 还有这么简单、快速的后端支持库。

FastAPI 官档地址:

https://fastapi.tiangolo.com/zh/

下面先列出几个需要 Review 的 PR,希望大家多多参与。

  • https://github.com/tiangolo/fastapi/pull/3826

  • https://github.com/tiangolo/fastapi/pull/3827

  • https://github.com/tiangolo/fastapi/pull/3828

以下为正文。
顺祝大家十一快乐。


查询参数

声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name""Foo"}, {"item_name""Bar"}, {"item_name""Baz"}]


@app.get("/items/")

async def read_item(skip: int = 0, limit: int = 10):

    return fake_items_db[skip : skip + limit]

查询字符串是键值对的集合,这些键值对位于 URL 的 ? 之后,以 & 分隔。

例如,以下 URL 中:

http://127.0.0.1:8000/items/?skip=0&limit=10

……查询参数为:

  • skip:值为 0

  • limit:值为 10

这些值都是 URL 的组成部分,因此,它们的类型本应是字符串。

但声明 Python 类型(上例中为 int)之后,这些值就会转换为声明的类型,并进行类型校验。

默认值

查询参数不是路径的固定内容,它是可选的,还支持默认值。

上例用 skip=0limit=10 设定默认值。

访问 URL:

http://127.0.0.1:8000/items/

与访问以下地址相同:

http://127.0.0.1:8000/items/?skip=0&limit=10

但如果访问:

http://127.0.0.1:8000/items/?skip=20

查询参数的值就是:

  • skip=20:在 URL 中设定的值

  • limit=10:使用默认值

可选参数

同理,把默认值设为 None 即可声明可选的查询参数:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")

async def read_item(item_id: str, q: Optional[str] = None):

    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

本例中,查询参数 q 是可选的,默认值为 None

!!! check "检查"

注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。

!!! note "笔记"

因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。

FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。

查询参数类型转换

参数还可以声明为 bool 类型,FastAPI 会自动转换参数类型:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")

async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):

    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description""This is an amazing item that has a long description"}
        )
    return item

本例中,访问:

http://127.0.0.1:8000/items/foo?short=1

http://127.0.0.1:8000/items/foo?short=True

http://127.0.0.1:8000/items/foo?short=true

http://127.0.0.1:8000/items/foo?short=on

http://127.0.0.1:8000/items/foo?short=yes

或其它任意大小写形式(大写、首字母大写等),函数接收的 short 参数都是布尔值 True。值为 False 时也一样。

多个路径和查询参数

FastAPI 可以识别同时声明的多个路径参数和查询参数。

而且声明查询参数的顺序并不重要。

FastAPI 通过参数名进行检测:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()



@app.get("/users/{user_id}/items/{item_id}")

async def read_user_item(

    user_id: int, item_id: str, q: Optional[str] = None, short: bool = False

)
:

    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description""This is an amazing item that has a long description"}
        )
    return item

必选查询参数

为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就不是必选的了。

如果只想把参数设为可选,但又不想指定参数的值,则要把默认值设为 None

如果要把查询参数设置为必选,就不要声明默认值:

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

这里的查询参数 needy 是类型为 str 的必选查询参数。

在浏览器中打开如下 URL:

http://127.0.0.1:8000/items/foo-item

……因为路径中没有必选参数 needy,返回的响应中会显示如下错误信息:

{
    "detail": [
        {
            "loc": [
                "query",
                "needy"
            ],
            "msg""field required",
            "type""value_error.missing"
        }
    ]
}

needy 是必选参数,因此要在 URL 中设置值:

http://127.0.0.1:8000/items/foo-item?needy=sooooneedy

……这样就正常了:

{
    "item_id""foo-item",
    "needy""sooooneedy"
}

当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:

from typing import Optional

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: Optional[int] = None

)
:

    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

本例中有 3 个查询参数:

  • needy,必选的 str 类型参数

  • skip,默认值为 0int 类型参数

  • limit,可选的 int 类型参数



!!! tip "提示"

还可以像在[路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`


如果您对 FastAPI 感兴趣,请在公号后台输入 fastapi

浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报