from fastapi import FastAPI, Response, Cookie
import secrets
app = FastAPI()
@app.get("/set_cookie")
async def set_cookie(response: Response):
token = secrets.token_hex(32)
response.set_cookie(
key="x-token",
value=token,
max_age=0,
secure=True
)
print(token)
return {"message": "Cookie is set"}
@app.get("/get_cookie")
async def get_cookie(token: str = Cookie(token)):
print(token)
return {"cookie_value": token}
@app.post('token')
async def set_token() -> JSONResponse:
token = secrets.token_hex(32)
resp = JSONResponse(content={'new_token': token})
resp.set_cookie(key='x_token', value=token, secure=True)
return resp
@app.get('token')
async def get_token(x_token: str = Cookie()) -> JSONResponse:
return {'token': x_token}