简体   繁体   English

为什么我会得到这个? “NameError:名称'响应'未定义”

[英]Why am I getting this? “NameError: name 'Response' is not defined”

I'm trying to get data from another of my servers.我正在尝试从我的另一台服务器获取数据。 The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata , I get this error:另一台服务器只是一个带有“Hello World”的 html 文件,我可以正常访问我的主页,但是当我将 go 转到/farmdata时,我收到此错误:

NameError: name 'Response' is not defined" NameError:名称“响应”未定义”

from flask import Flask, render_template
import requests


app = Flask(__name__)

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

@app.route('/farmdata')
def farmdata():
    r = requests.get('http://74.114.75.91:8080')
    r.url
    r.encoding
    return Response(
        r.text,
        status=r.status_code,
        content_type=r.headers['content-type'],
    )

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

Edit - to anyone else with the problem, this was the solution.编辑 - 对于其他有问题的人,这就是解决方案。

from flask import Flask, render_template, Response

You have never defined Response .您从未定义Response If you want to use flask.Response , you either have to import flask and then access it via flask.Response , or from flask import Response and then simply use Response . If you want to use flask.Response , you either have to import flask and then access it via flask.Response , or from flask import Response and then simply use Response .

In your code, you import Flask from the flask module, and that's where you get Flask from.在您的代码中,您从flask模块导入Flask ,这就是您从中获得Flask的地方。 If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.如果删除from flask import Flask行,您将收到NameError抱怨Flask也未定义。

In Python, a name is defined if:在 Python 中,在以下情况下定义名称:

  • you defined it via variable assignment [or with a def or a class statement, which is pretty much the same] (like app in your example)您通过变量赋值定义它[或使用defclass语句,几乎相同](如您示例中的app
  • you imported it from another module explicitly (like Flask )您从另一个模块显式导入它(如Flask
  • it's defined on startup (like list )它是在启动时定义的(如list

Is there not a "," too much before closing the brackets of the response?在关闭响应的括号之前没有太多的“,”吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM