Why am I getting this? "NameError: name 'Response' is not defined"

11,669

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)
Share:
11,669
The Candy King
Author by

The Candy King

Owner and COT of Everyday Mushrooms

Updated on June 04, 2022

Comments

  • The Candy King
    The Candy King almost 2 years

    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
    
    • Olvin Roght
      Olvin Roght almost 4 years
      from flask import Response
  • decorator-factory
    decorator-factory almost 4 years
    Trailing commas are valid in Python. This has nothing to do wtih the NameError.
  • The Candy King
    The Candy King almost 4 years
    Thanks for the comment, while like the others say it is not the error, I do like to have my code formatted correctly. I make enough mistakes already, I don't need to make more because of bad formatting
  • The Candy King
    The Candy King almost 4 years
    I've tried that. When I put in this ``` from flask import Flask, render_template, import Response ``` I get "SyntaxError: invalid syntax"
  • Olvin Roght
    Olvin Roght almost 4 years
    @TheCandyKing try to delete last import from your example
  • decorator-factory
    decorator-factory almost 4 years
    The correct syntax is either import Module, from Module import *, from Module import a, b, c, from Module import a as my_a, b, c, d as hello_world. More on imports: docs.python.org/3/tutorial/modules.html, realpython.com/python-modules-packages