NameError: name 'request' is not defined

PythonFlask

Python Problem Overview


I got this Python Code, and somehow I get the Error Message:

> File "/app/identidock.py", line 13, in mainpage > if request.method == 'POST': > NameError: name 'request' is not defined

But I really can't find my mistake. Can someone please help me with that?

from flask import Flask, Response
import requests
import hashlib

app = Flask(__name__)
salt = "UNIQUE_SALT"
default_name = 'test'

@app.route('/', methods=['GET', 'POST'])
def mainpage():

    name = default_name
    if request.method == 'POST':
        name = request.form['name']

    salted_name = salt + name
    name_hash = hashlib.sha256(salted_name.encode()).hexdigest()

    header = '<html><head><title>Identidock</title></head><body>'
    body = '''<form method="POST">
              Hallo <input type="text" name="name" value="{0}">
              <input type="submit" value="Abschicken">
              </form>
              <p> Du siehst aus wie ein: </p>
             <img src="/monster/{1}"/>
           '''.format(name, name_hash)
    footer = '</body></html>'

    return header + body + footer

@app.route('/monster/<name>')
def get_identicon(name):

    r = requests.get('http://dnmonster:8080/monster/' \
        + name + '?size=80')
    image = r.content

    return Response(image, mimetype='image/png')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

Python Solutions


Solution 1 - Python

You appear to have forgotten to import the flask.request request context object:

from flask import request

Solution 2 - Python

You are probably missing the following import statement:

from flask import request

that should be placed in the header of the file.

Solution 3 - Python

This is because you missed the import statement

from flask import request

Solution 4 - Python

Use this will Work,

> self.request

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeonard MichalasView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonWillem Van OnsemView Answer on Stackoverflow
Solution 3 - PythonCodemakerView Answer on Stackoverflow
Solution 4 - Pythonshoaib21View Answer on Stackoverflow