python - Flask View 引发 TypeError : 'bool' object is not callable

标签 python flask flask-login

我正在尝试调试我的 Flask 应用程序中的一个 View ,该 View 返回 500 状态,回溯中出现错误 TypeError: 'bool' object is not callable。 View 从 Flask-Login 调用 login_user 然后返回 True 以指示登录成功。

我一直在调试,直到 app_iter = app(environ, start_response) 并且 app 现在是一个值为 True 的 bool 值,而不是Flask 应用程序对象。

Traceback (most recent call last):
  File "D:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "D:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Python27\lib\site-packages\flask\app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "D:\Python27\lib\site-packages\flask\app.py", line 1577, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "D:\Python27\lib\site-packages\werkzeug\wrappers.py", line 824, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "D:\Python27\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "D:\Python27\lib\site-packages\werkzeug\test.py", line 854, in run_wsgi_app
    app_iter = app(environ, start_response)
TypeError: 'bool' object is not callable
@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    user = User.query.filter_by(username=username).first()

    if user:
        login_user(user)
        return True

    return False

最佳答案

在 Flask 中, View 必须返回以下之一:

  • 一个字符串
  • Response 对象(或子类)
  • (string, status, headers)(string, status) 的元组>
  • 一个有效的 WSGI 应用程序

Flask 测试前 3 个选项,如果它们不适合,则假定它是第四个。您在某处返回了 True,它被视为 WSGI 应用程序。

参见 About Responses在文档中。

关于python - Flask View 引发 TypeError : 'bool' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406057/

相关文章:

python - 检查字符串是否在python中按字母顺序排列

python - 将 Flask-Injector 与 Flask-restplus 一起使用会导致调用 api 资源时出错

python - Flask 登录和委托(delegate)人 - 即使我已登录,current_user 也是匿名的

python - Flask_login.current_user.is_authenticated 与 Flask-dance facebook.authorized

python - 如果通过某些路由访问,请禁用 WTForms CSRF

python - 名称错误 : name of the class not defined inside the class itself - python

python - Redis 过期通知和 Flask

python - 检查二维列表中的每个元素

python - flask - 何时关闭 mysql 连接?

python - 用户可以在 Flask URL 参数中使用的限制值