Python Flask Basics Character Builder Cookies

Logan R
Logan R
22,823 Points

NameError: name 'request' is not defined

When I try to run this code, it gives me the following error:

builtins.NameError
NameError: name 'request' is not defined

Traceback (most recent call last)
File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Logan\Desktop\python server\Stage 3 Start\app.py", line 13, in save
response.set_cookie('character', json.dumps(dict(request.form.items())))
NameError: name 'request' is not defined

Here is my code:

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

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

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

# Runs the app in debug mode. The server will restart after each save automatically.
app.run(debug=True, port=8000, host='localhost')

1 Answer

Logan R
Logan R
22,823 Points

I didn't include request in my import statements...I had redirect twice instead. Including request fixed my problem.