Jake
Jake

Reputation: 1223

check exist post value in 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.

Upvotes: 2

Views: 8812

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124070

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'

Upvotes: 9

Related Questions