FastAPI学习笔记(一)-14.请求头cookie和head

FastAPI学习笔记(一)-14.请求头cookie和head
 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: chapter036.py
 5 @contact:invoker2021@126.com
 6 @descript:
 7 @Date:2021/8/6 21:50
 8 @version: Python 3.7.8
 9 '''
10 from fastapi import APIRouter,Cookie,Header
11 from typing import Optional,List
12 
13 app036 = APIRouter()
14 
15 """Cookie 和 Header"""
16 # 这个接口只能在postman中执行,在线api文档不能执行
17 @app036.get("/cookie")
18 async def cookie(cookie_id:Optional[str] = Cookie(None)):
19     return{"cookie_id":cookie_id}
20 
21 @app036.get("/header")
22 async def header(user_agent:Optional[str] = Header(None,convert_underscores=True),
23                  x_token:List[str] = Header(None)):
24     return {"user-agent":user_agent,"x_token":x_token}
View Code

/cookie接口需要用postman来执行

且用到了Cookie类,来自 from fastapi import Cookie

FastAPI学习笔记(一)-14.请求头cookie和head

 

 /header接口

且用到了Header类,来自 from fastapi import Header

请求体:

curl -X 'GET' \ 'http://127.0.0.1:8000/chapter036/header' \ -H 'accept: application/json' \ -H 'x-token: string1,string2,string3'

返回:

{ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36", "x_token": [ "string1,string2,string3" ] }

上一篇:FastAPI响应系列(二) 响应状态码


下一篇:FastAPI数据库系列(一) MySQL数据库操作