Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie in Python Flask?

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

like image 561
Shaon shaonty Avatar asked Oct 10 '17 07:10

Shaon shaonty


People also ask

How do I set cookies in Python?

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.

What is cookie and why is it write a simple program using Flask?

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.

What is session and cookies in Flask?

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.

How do you secure a cookie in Flask?

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.


1 Answers

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') 
like image 53
Sahid Hossen Avatar answered Sep 26 '22 02:09

Sahid Hossen