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?
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.
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.
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.
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 .
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')))
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