Skip to content
Advertisement

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?

Advertisement

Answer

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

Advertisement