Right way to catch KeyError in Django?

I am creating an API where the url is sent to the server. I want to get a username, etc. From URL. For this, I use the following code:

 try:
    username = request.REQUEST['username']
    message  = request.REQUEST['message']
    time = request.REQUEST['time']

 except KeyError:
    ...

However, there are times when the URL does not contain a username, message, time, etc. In this case, a KeyError occurs. I want to be able to catch this and find out which parameter is missing, so I can issue an error response code that tells the user which parameter is missing. In the exclusion area, is there a way to determine where the code failed to execute?

+3
source share
2 answers

Not bad. Use the default value Noneand check after.

try:
  username = request.REQUEST.get('username', None)
   ...
except ...:
   ...
else:
  if username is None:
     ...
+1

?

if 'username' in request.REQUEST:
    username = request.REQUEST['username']
else:
    #username not found
+1

Source: https://habr.com/ru/post/1760444/


All Articles