Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"TypeError": 'list' object is not callable flask

Tags:

python

flask

I am trying to show the list of connected devices in browser using flask. I enabled flask on port 8000:

in server.py:

@server.route('/devices',methods = ['GET'])
def status(): 
    return app.stat()

if __name__ == '__main__':
        app.run()

in app.py:

def stat():
    return(glob.glob("/dev/tty57") + glob.glob("/dev/tty9"))

And this is my test:

url = "http://127.0.0.1:8000"

response = requests.get(url + "").text
print response

but I keep getting this error:

"TypeError": 'list' object is not callable.

Am I doing sth wrong in checking if ttyUSB, ... and other devices existing?

like image 948
N45 Avatar asked Dec 22 '14 19:12

N45


People also ask

How do I fix TypeError list object is not callable?

The Python "TypeError: 'list' object is not callable" occurs when we try to call a list as a function using parenthesis () . To solve the error, make sure to use square brackets when accessing a list at a specific index, e.g. my_list[0] .

How do I fix TypeError int object is not callable?

How to resolve typeerror: 'int' object is not callable. To resolve this error, you need to change the name of the variable whose name is similar to the in-built function int() used in the code. In the above example, we have just changed the name of variable “int” to “productType”.

Why is something not callable in Python?

The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int() , sum() , max() , and others. The error also occurs when you don't specify an arithmetic operator while performing a mathematical operation.

Why is my class not callable Python?

Python attempts to invoke a module as an instance of a class or as a function. This TypeError: 'module' object is not callable error occurs when class and module have the same name. The import statement imports the module name not the class name.


1 Answers

The problem is that your endpoint is returning a list. Flask only likes certain return types. The two that are probably the most common are

  • a Response object
  • a str (along with unicode in Python 2.x)

You can also return any callable, such as a function.

If you want to return a list of devices you have a couple of options. You can return the list as a string

@server.route('/devices')
def status():
    return ','.join(app.statusOfDevices())

or you if you want to be able to treat each device as a separate value, you can return a JSON response

from flask.json import jsonify

@server.route('/devices')
def status():
    return jsonify({'devices': app.statusOfDevices()})
    # an alternative with a complete Response object
    # return flask.Response(jsonify({'devices': app.statusOfDevices()}), mimetype='application/json')
like image 186
dirn Avatar answered Oct 06 '22 14:10

dirn