当有人点击 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)
Option 1
Use the Request
对象获取您想要的 cookie,如中所述星光文档.
from fastapi import Request
@app.get('/')
async def root(request: Request):
return request.cookies.get('sessionKey')
Option 2
Use the Cookie
参数,如中所述FastAPI文档。附带说明一下,下面的示例将 cookie 参数定义为optional,使用类型Union[str, None]
;然而,还有其他方法可以做到这一点(例如,str | None
在 Python 3.10+ 中)—看看这个答案 and 这个答案更多细节。
from fastapi import Cookie
from typing import Union
@app.get('/')
async def root(sessionKey: Union[str, None] = Cookie(None)):
return sessionKey
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)