Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set default value for form data in Flask

Tags:

python

flask

I have a Flask route, defined like this:

@app.route('/test/', methods=['POST'])
def test():
    number = request.form.get('my_number', 555) # number == ''
    return str(number)

If I make a POST request to /test/ with my_number empty/missing, I expect the local variable number to be set to 555 (the default). Instead, number is an empty string ''.

The only way I'm able to get the default value to be respected (number == 555) is to use or like this:

@app.route('/test/', methods=['POST'])
def test():
    number = request.form.get('my_number') or 555 # number == 555
    return str(number)

Any idea what's going wrong?

like image 701
tzazo Avatar asked Sep 06 '25 03:09

tzazo


1 Answers

The issue is that for your input, request.form.get('number') is always retrieving an empty string. Because there is something to retrieve, it never uses the default value even if you pass it as the second parameter.

or, however, treats '' as false, so it will pick 555. (see "Using or With Common Objects" https://realpython.com/python-or-operator/)

This implies that whenever you are accessing this url, the form you are posting has an entry for "number".

like image 101
sd191028 Avatar answered Sep 07 '25 16:09

sd191028