Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Flask Basics Character Builder Cookies

Ayman Said
seal-mask
.a{fill-rule:evenodd;}techdegree
Ayman Said
Python Web Development Techdegree Student 14,717 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 67,995 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!!