Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check exist post value in Python Flask

Tags:

python

flask

How can I check exist post value in python flask?

I am a PHP programmer, and it will be like this in PHP.

function profile_update()
{
    if($this->input->post('photo))
    {
        echo 'photo is exist';
    }else{
        echo 'photo is not exist';
    }
}

I would like to make like this in python flask, but it makes an error.

@app.route('/apis/settings/profile_update_submit', methods=['POST'])
def settings_profile_update_submit_test():
    now = datetime.datetime.utcnow()
    phone = request.form['phone']
    photo = request.file['photo']

if 'photo' in request.files:
    return 'photo exists'
else:
    return 'photo does not exist'

This keep showing 'photo does not exist' message even though I put a file in the form.

like image 605
Jake Avatar asked Nov 17 '25 22:11

Jake


1 Answers

Test for the file first:

@app.route('/apis/settings/profile_update_submit', methods=['POST'])
def settings_profile_update_submit_test():
    now = datetime.datetime.utcnow()
    phone = request.form['phone']

    if 'photo' in request.files:
        return 'photo exists'
    else
        return 'photo does not exist'

Trying to access a non-existing key will raise a KeyError exception otherwise.

You can also use .get(key, default) to return a default (None if you omit a more specific default):

photo = request.files.get('photo')
if photo is not None:
    return 'photo exists'
else
    return 'photo does not exist'
like image 149
Martijn Pieters Avatar answered Nov 20 '25 12:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!