Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask Basics Character Builder Cookies

I'm getting only empty value in the browser Cookies.

I'm getting only empty value in the browser Cookies. It is saying name='character' , value = "{}"

4 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Be sure you are merging the existing cookie data with the new data. Otherwise, if there is a merge error, then a empty dictionary is returned by default. Look at 4:50 in the video to review get_saved_data() function.

Running into the same thing trying to follow along on my machine. Watched through the whole video twice, added the get_saved_data function

My cookie never updates with anything other than "{}"

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

# Define our routes

@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)

[MOD: added "python" to formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Can you confirm that new/any data is present in request.form.items()?

When I try the trace with PDB, my result for request.form is:

ImmuableMultiDict([])

Any idea what step I missed to populate this from the form submission?

Where else does he cover PDB, I'm on a custom track setup by my employer and I don't recall him talking through that on previous videos.

Found out what was going on with mine. I was trying to make it work with a custom form and was missing the name="name" attribute from my name text input on the form.