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

2021/8/6 23:09:40

本文主要是介绍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

 

 /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学习笔记(一)-14.请求头cookie和head的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程