Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a cookie in flask

I am trying to create a cookie in flask. The partial example in the manual is:

resp = make_response(render_template(...))
resp.set_cookie(’username’, ’the username’)

So I implement it as:

resp = render_template('show_entries.html', AO_sInteger = session.get('AO_sInteger'))
resp.set_cookie('AO_sInteger', AO_sInteger)

The system then returns this error:

File "...\Flaskr101.py", line 19, in add_entry
resp.set_cookie('AO_sInteger', AO_sInteger)
AttributeError: 'unicode' object has no attribute 'set_cookie'

How can I fix this problem?

like image 257
Dr Ottensooser Avatar asked Aug 02 '12 08:08

Dr Ottensooser


People also ask

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.

How do you make multiple cookies in Flask?

Setting cookies in Flask Cookies are set on the response object in Flask. First, we initialize a response object with make_response() and then attach the cookie key: value pair to this object with the help of the set_cookie() command.

Are Flask sessions cookies?

In order to store data across multiple requests, Flask utilizes cryptographically-signed cookies (stored on the web browser) to store the data for a session. This cookie is sent with each request to the Flask app on the server-side where it's decoded.

Does Flask support secure cookies?

The secure flag for Flask's session cookie can be enabled in the Flask configuration. To set it for other cookies, pass the secure flag to response. set_cookie .


1 Answers

In the manual resp is:

resp = make_response(render_template(...))

and in your code it is:

resp = render_template('show_entries.html', 
                        AO_sInteger = session.get('AO_sInteger'))

Make it a proper response object by using make_response:

from flask import make_response
resp = make_response(render_template('show_entries.html',
                                      AO_sInteger = session.get('AO_sInteger')))
like image 155
NIlesh Sharma Avatar answered Sep 30 '22 19:09

NIlesh Sharma