The Candy King
The Candy King

Reputation: 89

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:

NameError: name 'Response' is not defined"

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

Upvotes: 3

Views: 26012

Answers (2)

decorator-factory
decorator-factory

Reputation: 3083

You have never defined 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. If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.

In Python, a name is defined if:

  • 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)
  • you imported it from another module explicitly (like Flask)
  • it's defined on startup (like list)

Upvotes: 4

Serge
Serge

Reputation: 29

Is there not a " ," too much before closing the brackets of the response?

Upvotes: -1

Related Questions