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

Last updated