“TypeError”:“列表”对象不是可调用的瓶子 [英] "TypeError": 'list' object is not callable flask

查看:121
本文介绍了“TypeError”:“列表”对象不是可调用的瓶子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用浏览器在浏览器中显示连接的设备列表。我启用了端口8000上的烧瓶:



在server.py中:

  @ server.route('/ devices',methods = ['GET'])
def status():
return app.stat()
$ b $ if __name__ == '__main__':
app.run()

在app.py中:

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

这是我的测试:

  url =http://127.0.0.1:8000

response = requests.get(url +).text
打印回应

但是我一直收到这个错误:

 TypeError:list对象不可调用。 

我在检查ttyUSB,...和其他设备是否存在错误?

解决方案

问题是您的端点正在返回一个列表。 Flask只喜欢某些返回类型。这可能是最常见的两种:


  • a 回应 object

  • a str (以及Python 2.x中的 unicode



  • 您还可以返回任何可调用对象,如函数。

    如果您想返回一个设备列表,你有几个选项。您可以将列表作为字符串返回

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

    您希望能够将每个设备视为一个单独的值,您可以从flask.json中返回一个JSON响应

      import jsonify 

    @ server.route('/ devices')
    def status():
    返回jsonify({'devices':app.statusOfDevices()})
    #一个完整的Response对象的替代
    #return flask.Response(jsonify({'devices':app.statusOfDevices()}),mimetype ='application / json')


    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?

    解决方案

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

    这篇关于“TypeError”:“列表”对象不是可调用的瓶子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆