FastAPI 教程翻译 - 用户指南 14 - Header 参数

FastAPI 教程翻译 - 用户指南 14 - Header 参数

FastAPI Tutorial - User Guide - Header Parameters

You can define Header parameters the same way you define Query, Path and Cookie parameters.

您可以使用定义 QueryPathCookie 参数的方法来定义 Header 参数。

Import Header

导入 Header

First import Header:

首先导入 Header

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

Declare Header parameters

声明 Header 参数

Then declare the header parameters using the same structure as with Path, Query and Cookie.

然后使用与 PathQueryCookie 相同的结构声明 Header 参数。

The first value is the default value, you can pass all the extra validation or annotation parameters:

第一个值是默认值,您可以传递所有其他验证或注释参数:

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

Technical Details

技术细节

Header is a “sister” class of Path, Query and Cookie. It also inherits from the same common Param class.

HeaderPathQueryCookie 的『姐妹』类。它也继承自相同的通用 Param 类。

But remember that when you import Query, Path, Header, and others from fastapi, those are actually functions that return special classes.

但是请记住,当您从 fastapi 中导入 QueryPathHeader 和其他文件时,这些实际上是返回特殊类的函数。

Info

信息

To declare headers, you need to use Header, because otherwise the parameters would be interpreted as query parameters.

要声明 Header,您需要使用 Header,否则参数将被解释为查询参数。

Automatic conversion

自动转换

Header has a little extra functionality on top of what Path, Query and Cookie provide.

HeaderPathQueryCookie 的基础上具有一些额外的功能。

Most of the standard headers are separated by a “hyphen” character, also known as the “minus symbol” (-).

大多数标准 header 由『连字符』(也称为『减号』)(-)分隔。

But a variable like user-agent is invalid in Python.

但是像 user-agent 这样的变量在 Python 中无效。

So, by default, Header will convert the parameter names characters from underscore (_) to hyphen (-) to extract and document the headers.

因此,默认情况下,Header 会将参数名称字符从下划线(_)转换为连字符(-),以提取并记录 header。

Also, HTTP headers are case-insensitive, so, you can declare them with standard Python style (also known as “snake_case”).

另外,HTTP header 不区分大小写,因此,您可以使用标准 Python 样式(也称为『snake_case』)声明它们。

So, you can use user_agent as you normally would in Python code, instead of needing to capitalize the first letters as User_Agent or something similar.

因此,您可以像在 Python 代码中一样正常使用 user_agent,而无需将首字母大写为 User_Agent 或类似名称。

If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter convert_underscores of Header to False:

如果由于某种原因需要禁用下划线自动转换为连字符,请将 Header 的参数 convert_underscores 设置为 False

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, strange_header: str = Header(None, convert_underscores=False)):
    return {"strange_header": strange_header}

Warning

警告

Before setting convert_underscores to False, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.

在将 convert_underscores 设置为 False 之前,请记住,某些 HTTP 代理和服务器禁止使用带下划线的 header。

Duplicate headers

header 重复

It is possible to receive duplicate headers. That means, the same header with multiple values.

可能会收到重复的 header。也就是说,同一个 header 具有多个值。

You can define those cases using a list in the type declaration.

您可以使用类型声明中的列表来定义这些情况。

You will receive all the values from the duplicate header as a Python list.

您将从重复 header 中将所有值作为一个 Python 的 list 接收。

For example, to declare a header of X-Token that can appear more than once, you can write:

例如,要声明可以多次出现的 X-Token 的 header,可以编写:

from typing import List

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(x_token: List[str] = Header(None)):
    return {"X-Token values": x_token}

If you communicate with that path operation sending two HTTP headers like:

如果您与该路径操作通信,则发送两个 HTTP header,例如:

X-Token: foo
X-Token: bar

The response would be like:

{
    "X-Token values": [
        "bar",
        "foo"
    ]
}

Recap

回顾

Declare headers with Header, using the same common pattern as Query, Path and Cookie.

使用与 QueryPathCookie 相同的通用模式,用 Header 声明 header。

And don’t worry about underscores in your variables, FastAPI will take care of converting them.

不用担心变量中的下划线,FastAPI 将负责转换它们。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值