18
votes

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?

1
Which line are you getting the error? - Bhargav Rao♦
is there code missing or why have you imported requests and serial in app.py? - Padraic Cunningham
The browser return "Internal server error". when I use "gunicorn server:server -b 0.0.0.0:8000" command I see the error.In app.py when I change the glob.glob ... to return "test result" everything works fine. - N45
Given that Flask allows for single-page apps, why is this split into multiple files at all? Even if a reproducer couldn't be done with no Flask at all (and if this can be reproduced without Flask, it should be reproduced without Flask -- see stackoverflow.com/help/mcve), it still should be able to be only one file, to allow easier reproduction with the same line numbers (because you should be showing us a stack trace with line numbers). - Charles Duffy
Thanks Charles for your comment. I want to add multiple endpoints later and run multiple tests in different directories that's why I put everything in separate files. - N45

1 Answers

32
votes

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