【7.0】Fastapi的Cookie和Header参数

发布时间 2023-10-01 16:15:20作者: Chimengmeng

【一】Cookie 操作

【1】定义视图函数

from fastapi import APIRouter, Path, Query,Cookie,Header
from typing import Optional

app03 = APIRouter()
## Cookie 和 Header 参数
# 因为 cookie 是浏览器的操作,所以只能用 接口测试工具测试,不能用fastapi自带的文档
@app03.get('/cookie')
async def cookie(cookie_id: Optional[str] = Cookie(None)):
    return {"cookie_id": cookie_id}

【2】发起请求

  • 通过 docs 获取到详细的请求地址

image-20230929233046425

  • 使用 postman 发起请求

image-20230929233252875

【二】Header 操作

【1】定义视图

from fastapi import APIRouter, Path, Query, Cookie, Header
from typing import List
from typing import Optional

@app03.get('/header')
# convert_underscores 是否转换下划线  (user_agent --> user-agent)
async def header(user_agent: Optional[str] = Header(None, convert_underscores=True),
                 x_token: Optional[str] = Header(None)):
    """
    有些HTTP代理和服务器是不允许在请求头中带有下划线的,所以Header提供convert_underscores属性让设置
    :param user_agent: convert_underscores=True 会把 user_agent 变成 user-agent
    :param x_token: x_token是包含多个值的列表
    :return:
    """
    return {"user_agent": user_agent, 'x_token': x_token}

【2】发起请求

  • 在 docs 查看请求路径

image-20230929233922590