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

Flask Basics - Cookies - 500 Internal Server Error

Hello everyone! I'm trying to use to Flask Basics course on my own webpage. Trying to get the form to save input information from a cookie exactly like how it's done in the course. However, I'm getting a 500 internal server error. Console is giving the following output.

app.py", line 8, in get_saved_data
    data = json.loads(request.cookies.get('character'))
NameError: global name 'request' is not defined

Here is my code:

import json
from flask import Flask, render_template, redirect, url_for, make_response

app = Flask(__name__)

def get_saved_data():
        data = json.loads(request.cookies.get('character'))
    except TypeError:
        data = {}
    return data

def index():
    data = get_saved_data()
    return render_template('index.html', saves=data)

@app.route('/email', methods=['POST'])
def email():
    response = make_response(redirect(url_for('index')))
    data = get_saved_data()
    response.set_cookie('character', json.dumps(data))
    return response
<form action="{{ url_for('email') }}" method=POST class="form_class">
<div class="row">
<div class="mew_form clearfix">
  <div class="col-sm-12" id="result"></div>

<div class="col-sm-6">

<input value="{{ saves.get('name', 'Name')}}" placeholder="Your Name" class="form_inputs" id="name" name="name" required="required">

<div class="col-sm-6">

<input value="{{ saves.get('email', 'Email')}}" placeholder="Your Email" class="form_inputs" id="email" name="email" required="required">


 <div class="col-sm-12">

 <textarea value="{{ saves.get('message', 'Message')}}" placeholder="Your Message" class="form_inputs form_textarea" id="message" name="message" required="required"></textarea>


 <div class="col-xs-12">

<div class="button_div  center_on_mobile">
<input id="submit_handle" type="submit" style="display: none" />
<a href="#" id="submit_btn" class="bg_pink button button_default_style open_sans bg_before_navy"> <i class="fa fa-envelope" aria-hidden="true"></i> Send Message</a>






1 Answer

it seems like you forgot to import request.

from flask import request