【问题标题】:How to get the cookies from an HTTP request using FastAPI?如何使用 FastAPI 从 HTTP 请求中获取 cookie?
【发布时间】:2023-02-10 14:54:14
【问题描述】:
是否可以在有人点击 API 时获取 cookie?我需要读取每个请求的 cookie。
@app.get("/")
async def root(text: str, sessionKey: str = Header(None)):
print(sessionKey)
return {"message": text+" returned"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=5001 ,reload=True)
【问题讨论】:
标签:
python
http
cookies
fastapi
starlette
【解决方案1】:
您可以按照与访问示例中的标头相同的方式来执行此操作(请参阅docs):
from fastapi import Cookie
@app.get("/")
async def root(text: str, sessionKey: str = Header(None), cookie_param: int | None = Cookie(None)):
print(cookie_param)
return {"message": f"{text} returned"}
【解决方案2】:
选项1
使用 Request 对象获取您想要的 cookie,如 Starlette documentation 中所述。
from fastapi import Request
@app.get('/')
async def root(request: Request):
print(request.cookies.get('sessionKey'))
return 'OK'
选项 2
使用 Cookie 参数,如 FastAPI documentation 中所述。
from fastapi import Cookie
@app.get('/')
async def root(sessionKey: str = Cookie(None)):
print(sessionKey)
return 'OK'