Home >Backend Development >Python Tutorial >Why Does My Flask View Return a `TypeError: 'bool' object is not callable`?

Why Does My Flask View Return a `TypeError: 'bool' object is not callable`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 06:02:10934browse

Why Does My Flask View Return a `TypeError: 'bool' object is not callable`?

Flask View TypeError: 'bool' Object Not Callable

In Flask, views are expected to return specific data types, namely: strings, Response objects, tuples of strings and status codes, or valid WSGI applications. However, returning a boolean value can lead to the error: TypeError: 'bool' object is not callable.

This occurs when the view function, instead of returning one of the aforementioned data types, returns a boolean (True or False). Flask interprets this boolean as a WSGI application and attempts to call it, resulting in the error.

To resolve this issue, ensure that the view function returns one of the supported data types. In the given code sample, the view returns True after successfully logging in a user:

@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

To rectify this, it should return a string, Response object, or tuple instead of the boolean:

@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 redirect(url_for('home'))  # Return a string or redirect

    return Response("Login failed", status=401)  # Return a Response object

The above is the detailed content of Why Does My Flask View Return a `TypeError: 'bool' object is not callable`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn