NameError:name' request'没有定义

时间:2017-01-05 14:25:05

标签: python flask

我有这个Python代码,不知怎的,我得到了错误信息:

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

但我真的无法找到我的错误。有人可以帮我吗?

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

5 个答案:

答案 0 :(得分:78)

您似乎忘记了导入flask.request request context对象:

from flask import request

答案 1 :(得分:13)

您可能遗漏了以下import声明:

from flask import request

应该放在文件的标题中。

答案 2 :(得分:2)

使用它会起作用,

self.request

答案 3 :(得分:0)

安装requests

pip install requests

并添加

from flask import request

到项目的第一行

答案 4 :(得分:0)

这是因为你错过了导入语句

from flask import request