FastAPI Cookie 参数,Header参数

# coding: utf8

from typing import Optional
from fastapi import FastAPI, Header, Cookie


app = FastAPI()

@app.get('/header')
async def header(user_agent: Optional[str] = Header(None)):
    return {"User-Agent": user_agent}


@app.get('/cookie')
async def cookie(cookie: Optional[str] = Cookie(None)):
    ''' cookie 当中指定的键值对'''
    return {"cookie": cookie}


@app.get('/users')
async def users(
    name: Optional[str] = Cookie(None),
    token: Optional[str] = Header(None, alias="X-Token"),
):
    if token is None or token != 'token':
        return {'code': 401, 'msg': 'No authority'}

    if name is None or name != 'admin':
        return {'code': 401, 'msg': 'Auth error'}
        
    return {'cookie_name': name, 'header_X_Token': token}


# # 启动: uvicorn main:app --reload

# User-Agent: PostmanRuntime/7.26.8
{
    "User-Agent": "PostmanRuntime/7.26.8"
}



# cookie: cookie=tom
{
    "cookie": "tom"
}


# 自定义 Header, Cookie

curl --location --request GET 'http://10.11.9.247:8000/users' \
--header 'cookie: name="admin"' \
--header 'X-Token: token

'
{
    "cookie_name": "admin",
    "header_X_Token": "token"
}

Last updated