FastAPI源码分析-Cookie和Header参数
FastAPI除了Path、Query、RequestBody参数外,还有Cookie和Header参数
Cookie参数
使用Cookie参数,需要引用Cookie类
1 2 3 4 5 6 7 8 | from fastapi import Cookie, FastAPI app = FastAPI() @app.get("/items/") async def read_items(*, ads_id: str = Cookie(None)): return {"ads_id": ads_id} |
Header参数
使用Header参数,需要引用Header类
1 2 3 4 5 6 7 8 | from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(*, user_agent: str = Header(None)): return {"User-Agent": user_agent} |
禁用自动转换
原始的Header参数中,参数名都是以"-“间隔,而且是大小写敏感的,FastAPI会自动进行转换,将”-“转换为”_",并将变量字符都转换为小写,如User-Agent会被自动转换为user_agent,如果不想进行这种默认的转换,可以设置convert_underscores为false
1 2 3 4 5 6 7 8 | from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(*, strange_header: str = Header(None, convert_underscores=False)): return {"strange_header": strange_header} |
重复的Headers
如果接收到重复的Header,一个键可能有多个值,也就是一个列表。
1 2 3 4 5 6 7 8 9 10 | from typing import List from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(x_token: List[str] = Header(None)): return {"X-Token values": x_token} |
例如,两次header中X-Token不一样
X-Token: foo
X-Token: bar
响应就是
{
“X-Token values”: [
“bar”,
“foo”
]
}
参考资料
- FastAPI官网 :https://fastapi.tiangolo.com/
- FastAPI源码 :https://github.com/tiangolo/fastapi