Flask:TypeError:' int'对象不可调用

时间:2014-06-07 09:02:52

标签: python flask typeerror

我是Python的新手,在我从事这个项目的过程中学习它,这个问题让我很困惑。这是我的代码:

from flask import Flask
from datetime import datetime

# Setup app
app = Flask(__name__)

# Initialize data dict
data = {}

# Pretty-formats a time difference
def formatdifference(delta):
    seconds = delta.total_seconds()
    if (seconds < 60):
        return "{seconds} seconds ago" % {"seconds": seconds}

    return "{minutes} minutes ago" % {"minutes": seconds/60}

# Sets a device battery level
@app.route("/set/<device>/<int:battery>")
def set(device, battery):
    data[device] = (battery, datetime.now())
    return "done"

# Get's a device battery level
@app.route("/get/<device>")
def get(device):
    if not device in data:
        return "No heartbeats"

    devicedata = data[device]
    delta = datetime.now() - devicedata[1]

    if (delta.total_seconds() > 10):
        return "Last heartbeat {diff}" % {"diff": formatdifference(delta)}

    return devicedata[0]

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')

我致电/set/phone/40。到目前为止都很好。然后我打电话给/get/phone。不太好。这是追溯:

TypeError: 'int' object is not callable
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1577, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 825, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/test.py", line 855, in run_wsgi_app
    app_iter = app(environ, start_response)
TypeError: 'int' object is not callable

使用flask的调试器,我可以看到在最后一帧中,app似乎是40!

这究竟是怎么发生的,我该如何解决?

1 个答案:

答案 0 :(得分:16)

您应该返回一个字符串对象,而不是一个int对象:

替换以下行:

return devicedata[0]

使用:

return str(devicedata[0])

或者,替换以下行:

data[device] = (battery, datetime.now())

使用:

data[device] = (str(battery), datetime.now())