UtsavShah
UtsavShah

Reputation: 877

Can Flask support an optional parameter in a POST request?

In the application, the user has a choice to upload a picture or not. But

picture_url = request.files['image']

seems to cause the page to stop loading the request if no such file exists. Is there any way to make this optional?

Upvotes: 2

Views: 3787

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121436

You are using syntax that throws an exception if the key is not present. Use .get() instead:

picture_url = request.files.get('image')

This returns None if the key was not set, e.g. no image field is present in the POST.

You could also handle the KeyError exception:

try:
    picture_url = request.files['image']
except KeyError:
    # no picture uploaded, do something else perhaps

Upvotes: 9

Related Questions