Hi 🙂🖐
Welcome to a new post, Today I will share with you how to set cookies in a web browser in FastAPI and Python in an easy way.
step 1
Import modules
from fastapi import FastAPI, Response, Request, Depends
from fastapi.responses import HTMLResponse
from secrets import token_hex
step 2
Create HTML file for test
<html>
<head></head>
<body>
<h1>This is test</h1>
</body>
</html>
step 3
Create test route
app = FastAPI()
@app.get('/test')
async def test(response: Response):
response = HTMLResponse(open('test.html', 'r').read())
response.set_cookie(key="fakesession", value=token_hex(20))
return response
run the API
uvicorn main:app --reload
it's working 😎
we have cookie
If you want to confirm if it really working 🙃
you can delete the cookie and reload the page 🙂
Read the cookie from another page
async def read_token(request : Request):
token = request.cookies.get('fakesession')
if not token:
return False
return token
@app.get('/protected')
async def protected(token : str = Depends(read_token)):
return {'token': token}
result
Now we're done 🤗
Don't forget to like and follow 🙂
Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396
Top comments (0)