Why does the Flask bool query parameter always evaluate to true?

Issue

I have an odd behavior for one of my endpoints in my Flask application which accepts boolean query parameters. No matter what I pass to it, such as asfsdfd or true or false, it is considered true. Only by leaving it empty does it become false.

full_info = request.args.get("fullInfo", default=False, type=bool)
if full_info:
    # do stuff

It seems to be that either any input is considered to be true. Is there any way to make this work with the Flask intended way of defining the type, or do I need to accept a string and compare it?

Solution

This is expected as query string is an actual string, hence when you get a string no matter what it is, if it’s not empty, it will be true.
As in:

>>>bool('False')
True

You will have to do string comparison if you want to get a boolean.

Answered By – dmitrybelyakov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published