In this way, I want to set my cookie. But it fails to set.
@app.route('/') def index(): res = flask.make_response() res.set_cookie("name", value="I am cookie")
When I print res
it shows <Response 0 bytes [200 OK]
But not set cookie
We use Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
The cookies are stored in the form of text files on the client's machine. Cookies are used to track the user's activities on the web and reflect some suggestions according to the user's choices to enhance the user's experience.
The session data is stored on the top of cookies and signed by the server cryptographically. In the flask, a session object is used to track the session data which is a dictionary object that contains a key-value pair of the session variables and their associated values.
Flask cookies should be handled securely by setting secure=True, httponly=True, and samesite='Lax' in response. set_cookie(...). If these parameters are not properly set, your cookies are not properly protected and are at risk of being stolen by an attacker.
You have to return the response after setting the cookie.
@app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('somecookiename', 'I am cookie') return resp
This way a cookie will be generated in your browser, but you can get this cookie in the next request.
@app.route('/get-cookie/') def get_cookie(): username = request.cookies.get('somecookiename')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With