Python Flask Basics Character Builder Cookies

Ayman Said
Ayman Said
Python Web Development Techdegree Student 11,620 Points

Any reason why Save() view has been changed? enhancement?

during the video save() view has been changed from:

    @app.route('/submitted', methods=['POST'])
    def save():
        response = make_response(redirect(url_for('index')))
        response.set_cookie('character', json.dumps(dict(request.form.items())))
        return response

To:

@app.route('/submitted', 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

What is the enhancement here? as from general design perspective, seems better to update an existing data structure, but anyway we are making it by dict(request.form.items()) ?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,951 Points

In the first code, the cookie is assigned based on the contents of the form.

But what if there are attributes in the cookie data that the form does not change or update. These would get cleared.

So, the second code retrieves all of the cookie information sent in the request, then updates this information with the new data from the form. Sort of a merge of old and new data. Finally, the merged data is returned in the response so all the cookies remain intact.

Post back if you need more help. Good luck!!