I defined an optional cookie parameter and now want to check if the cookie was set. Unfortunately, the variable does not equal to None but to an empty Cookie object. How can I check the cookie object if it is set?
Here's how I defined the cookie parameter:
@app.route("/graphcall")
def graphcall(request: Request, ads_id: Optional[str] = Cookie(None)):
if ads_id:
# Do stuff if the ads_id is set
I assume you tried this via SwaggerUI. Setting Cookie values currently does not work via SwaggerUI due to browser security restrictions.
@app.get("/items/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
if ads_id:
answer = "set to %s" % ads_id
else:
answer = "not set"
return {"ads_id": answer}
works perfectly from command line with Fastapi 0.61.0
$ curl -X GET "http://127.0.0.1:8000/items/" -H "accept: application/json" -H "Cookie: ads_id=foobar"
{"ads_id":"set to foobar"}
$ curl -X GET "http://127.0.0.1:8000/items/" -H "accept: application/json"
{"ads_id":"not set"}
For me this works
async def setcookie(request: Request, nm: str = Form(...)):
print("setcookie "+nm)
response = templates.TemplateResponse("readcookie.html",{"request": request})
response.set_cookie(key="userID", value=nm)
@app.get("/getcookie/", response_class=HTMLResponse)
async def getcookie(request: Request,userID: Optional[str] = Cookie(None)):
if userID:
print("getcookie "+userID)
else:
print("getcookie None")
return templates.TemplateResponse("showcookie.html", {"request": request, "name": userID})
In getcookie I have the cookie set in setcookie.
I follow this approach:
https://fastapi.tiangolo.com/advanced/response-cookies/#return-a-response-directly
I still don't understand why the Optional[str] = Cookie(None) method didn't work. For me this way worked
@router.post('/login')
async def sign_in(
user_data: OAuth2PasswordRequestForm = Depends(),
service: AuthService = Depends(),
):
session = await service.authenticate_user(
user_data.username,
user_data.password
)
response = RedirectResponse(url='/')
response.set_cookie('Authorization', value=session['session_id'], httponly=True)
return response
async def get_current_user(request: Request):
try:
cookie_authorization: str = request.cookies.get("Authorization")
# some logic with cookie_authorization
except Exception as e:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authentication"
)