Flask-restful: Argument of type `bool` evaluates all input to `True`

Created on 17 Feb 2015  路  3Comments  路  Source: flask-restful/flask-restful

class TestAPI(restful.Resource):

    reg_parser = reqparse.RequestParser()
    reg_parser.add_argument('test_bool', type=bool, location='form')

    def post(self):
        args = self.reg_parser.parse_args()

        return {
            'test_bool': args['test_bool']
            }
class TestTestCase(ApiTestCase):

    def test_bool_reg_parser(self):
        response = self.app.post(url_for('test_parser'), data={'test_bool': False})
        data = json.loads(response.data)


        assert data['test_bool'] == False
   Traceback (most recent call last):
    app/users/tests.py line 24 in test_bool_reg_parser
      assert data['test_bool'] == False
   AssertionError: 

print data
{u'test_bool': True}

Most helpful comment

This is because you can't use the python bool type to cast strings to boolean:

>>> bool('true')
True
>>> bool('false')
False

Python only considers a string "Falsy" if it is an empty string, all other strings are True:

>>> bool('')
False

TL;DR use flask_restful.inputs.boolean instead

All 3 comments

This is because you can't use the python bool type to cast strings to boolean:

>>> bool('true')
True
>>> bool('false')
False

Python only considers a string "Falsy" if it is an empty string, all other strings are True:

>>> bool('')
False

TL;DR use flask_restful.inputs.boolean instead

Thanks @joshfriend can you update this issue in docs? It would be pretty useful.

This is because you can't use the python bool type to cast strings to boolean:

>>> bool('true')
True
>>> bool('false')
False

@joshfriend I think you mean bool('false') is True...

Was this page helpful?
0 / 5 - 0 ratings