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
Release: 2024-12-10 06:02:10
Original
931 people have browsed it

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template