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 = "{}"

Amin Ruhul
Amin Ruhul
Pro Student 4,762 Points

What are you trying to do? any code example?

4 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,829 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.

Brian Weiss
Brian Weiss
4,632 Points

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 56,829 Points

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

Brian Weiss
Brian Weiss
4,632 Points

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.

Brian Weiss
Brian Weiss
4,632 Points

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.