Picking up request attribute with Python Json gives error

Asked

Viewed 242 times

0

I have the following code in my application in Flask:

from flask import request, json
cpf = request.json['cpf']

It works normally, but when there is no attribute in the json request it displays the error:

builtins.Keyerror
Keyerror: 'cnpj_cpf'

And for the execution, my doubt is how I can handle this request to be able to launch a Answer with code 400 (Bad Request) saying that the Cpf attribute is missing, without this "coding error"

2 answers

1


This error happens because there is no "cnpj_cpf" attribute in your request, you can exchange the call instead of using keys use the method get, example:

cpf = request.json.get('cpf', None)

In this case if there is no Cpf attribute in the request it returns None then you can give a Bad Request Answer:

cpf = request.json.get('cpf', None)

if not cpf:
    return make_response('Informe o CPF', 400)
  • Thank you very much, it worked 100% here, that’s what I needed!

1

You can handle the "Keyerror" error and launch an exception with a 404. Here’s something like this:

try:
   cpf = request.json['cpf']
except KeyError:
   return render_template('404.html'), 404

Browser other questions tagged

You are not signed in. Login or sign up in order to post.