FastAPI 教程翻译 - 用户指南 7 - 路径参数和数值验证

FastAPI 教程翻译 - 用户指南 7 - 路径参数和数值验证

FastAPI Tutorial - User Guide - Path Parameters and Numeric Validations

The same way you can declare more validations and metadata for query parameters with Query, you can declare the same type of validations and metadata for path parameters with Path.

可以使用 Query 为查询参数声明更多的验证和元数据,以相同的方式,可以使用 Path 声明相同类型的验证和路径参数的元数据。

Import Path

导入路径

First, import Path from fastapi: 首先,从 fastapi 导入 Path

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(..., title="The ID of the item to get"),
    q: str = Query(None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Declare metadata

声明元数据

You can declare all the same parameters as for Query.

您可以声明所有与 Query 相同的参数。

For example, to declare a title metadata value for the path parameter item_id you can type:

例如,要声明路径参数 item_idtitle 元数据值,您可以输入:

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(..., title="The ID of the item to get"),
    q: str = Query(None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Note

注意

A path parameter is always required as it has to be part of the path.

始终需要路径参数,因为它必须是路径的一部分。

So, you should declare it with ... to mark it as required.

因此,您应该使用 ... 声明它,以根据需要对其进行标记。

Nevertheless, even if you declared it with None or set a default value, it would not affect anything, it would still be always required.

但是,即使您使用 None 声明它或设置默认值,它也不会影响任何东西,但仍然总是需要它。

Order the parameters as you need

根据需要排序参数

Let’s say that you want to declare the query parameter q as a required str.

假设您要声明查询参数 q 为必需的 str

And you don’t need to declare anything else for that parameter, so you don’t really need to use Query.

而且您不需要为该参数声明其他任何内容,因此您实际上不需要使用 Query

But you still need to use Path for the item_id path parameter.

但是您仍然需要对 item_id 路径参数使用 Path

Python will complain if you put a value with a “default” before a value that doesn’t have a “default”.

如果将带有『默认值』的值放在没有『默认值』的值之前,Python 会报错。

But you can re-order them, and have the value without a default (the query parameter q) first.

但是您可以对其重新排序,并首先获得不带默认值的值(查询参数 q)。

It doesn’t matter for FastAPI. It will detect the parameters by their names, types and default declarations (Query, Path, etc), it doesn’t care about the order.

这个在 FastAPI 中不重要。它将通过参数的名称、类型和默认值声明(QueryPath等等)来检测参数,而不关心顺序。

So, you can declare your function as:

因此,您可以将函数声明为:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Order the parameters as you need, tricks

根据需要排序参数,技巧

If you want to declare the q query parameter without a Query nor any default value, and the path parameter item_id using Path, and have them in a different order, Python has a little special syntax for that.

如果要声明不带 Query 或任何默认值的 q 查询参数,以及不带 Path 的路径参数 item_id,并以不同的顺序排序,Python 对此有一些特殊的语法。

Pass *, as the first parameter of the function.

传递 *,作为函数的第一个参数。

Python won’t do anything with that *, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don’t have a default value.

Python 不会对该 * 做任何事情,但是它将知道以下所有参数都应称为关键字参数(键值对),也称为 kwargs。即使它们没有默认值,即无需关注参数的顺序(可以按照您希望的顺序排列参数)

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *, item_id: int = Path(..., title="The ID of the item to get"), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Number validations: greater than or equal

数字验证:大于等于

With Query and Path (and other’s you’ll see later) you can declare string constraints, but also number constraints.

使用 QueryPath(以及其他功能,您将在后面看到)可以声明字符串约束,但也可以声明数字约束。

Here, with ge=1, item_id will need to be an integer number “greater than or equal” to 1.

在这里,当 ge=1 时,item_id 必须是一个整数,大于等于 1

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *, item_id: int = Path(..., title="The ID of the item to get", ge=1), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Number validations: greater than and less than or equal

数字验证:大于和小于等于

The same applies for:

同样适用于:

  • gt: greater than 大于
  • le: less than or equal 小于等于
from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Number validations: floats, greater than and less than

数字验证:浮点数,大于和小于

Number validations also work for float values.

数字验证也适用于 float 值。

Here’s where it becomes important to be able to declare gt and not just ge. As with it you can require, for example, that a value must be greater than 0, even if it is less than 1.

在这里,能够声明 gt 而不只是 ge 变得很重要。与之类似,例如,您可以要求该值必须大于 0,即使该值小于 1 也是如此。

So, 0.5 would be a valid value. But 0.0 or 0 would not.

因此,0.5 将是有效值。但是 0.00 则不是。

And the same for lt.

lt 也是一样。

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(..., gt=0, lt=10.5)
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Recap

回顾

With Query, Path (and others you haven’t seen yet) you can declare metadata and string validations in the same ways as with Query Parameters and String Validations.

使用 Query、Path(以及您尚未看到的其他路径),您可以采用与 查询参数和字符串验证 相同的方式声明元数据和字符串验证。

And you can also declare numeric validations:

您还可以声明数字验证:

  • gt: greater than 大于
  • ge: greater than or equal 大于等于
  • lt: less than 小于
  • le: less than or equal 小于等于

Info

信息

Query, Path and others you will see later subclasses of a common Param class (that you don’t need to use).

QueryPath 和其他,您将在稍后看到一个常见的 Param 类的子类(不需要使用)。

And all of them share the same all these same parameters of additional validation and metadata you have seen.

并且所有这些共享相同的额外验证和元数据的相同参数。

Technical Details

技术细节

When you import Query, Path and others from fastapi, they are actually functions.

当您从 fastapi 导入 QueryPath 和其他时,它们实际上是函数。

That when called, return instances of classes of the same name.

调用时返回同名类的实例。

So, you import Query, which is a function. And when you call it, it returns an instance of a class also named Query.

因此,您将导入 Query,这是个函数。当您调用它时,它返回一个也称为 Query 的类的实例。

These functions are there (instead of just using the classes directly) so that your editor doesn’t mark errors about their types.

这些函数在那里(而不仅仅是直接使用类),以便您的编辑器不会标记有关其类型的错误。

That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.

这样,您可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值