Cookies are for storing data between requests that our users submit through the form.
Cookies are a great way for holding onto data, especially if we don’t want to use a database or JavaScripts’s local storage.
To do that, we should turn form submissions into JSON.
Note: Luckily, the JSON library is built into Python
First, we need to set the cookie in our save view using set_cookie( ).
Setting a cookie in Flask is a little weird, whereas in Flask cookies are set on the response (the things that goes back to the browser) which we don’t have until after the save function returns something. So we have to fake the response, using make_response()
#[app.py]
import json
@app.route('/save', methods=['POST'])
def save():
response = make_response(redirect( url_for('index')))
response.set_cookie('character', json.dumps(dict(request.form.items())))
return response
Explaining set_cookie()
set_cookie( cookie-name, cookie-value ) is a method of a response object. make_response( ) created that response object automatically.
- request.form Form data sent as an ImmutableMultiDict
- request.form.items( ) Gives a tuple of key & value pairs, taken from the form
- dict(request.form.items( )) Creates a dictionary from that tuple
- json.dumps(dict(request.form.items( )))) Creates a string from that dictionary
Now if you submit data into the form, inspect the resulted page in your browser and you’ll find the cookie that’s value is a dictionary with a key of ‘name’ and a value of ‘Mike’ or whatever the user submitted.
Re-using Cookie Data
If you’d like to re-use the submitted data in your app:
def get_save_data(): try: data = json.loads(request.cookies.get('character')) except TypeError: data = {} return data
json.dumps( ) Creates a JSON string
json.loads( ) Turns a JSON string into python code again (i.e. a Dictionary in our case)
@app.route('/') def index(): data = get_save_data() return render_template('index.html', saves=data)
App Files
[app.py]:
import json
from flask import (Flask, render_template, redirect,
url_for, request, make_response)
app = Flask(__name__)
def get_saved_data():
try:
data = json.loads(request.cookies.get('character'))
except TypeError:
data = {}
return data
@app.route('/')
def index():
data = get_saved_data()
return render_template('index.html', saves=data)
@app.route('/save', methods=['POST'])
def save():
response = make_response(redirect( url_for('index')))
data = get_saved_data()
data.update(dict(request.form.items()))
response.set_cookie('character', json.dumps(data))
return response
app.run(debug=True, host='0.0.0.0', port=8000)
[index.html]:
<input name="name" type="text" value="{{ saves.get('name', '') }}" autofocus="" />