tags:

views:

32

answers:

1

I am creating an API where a URL is sent to the server. I want to get the username, etc from the URL. I use the following code to do that:

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

 except KeyError:
    ...

However, there are times when the URL does not have a username, message, time, etc in it. In that case, a KeyError is raised. I want to be able to catch this and know which parameter was missing so I can issue an error response code that tells the user which parameter was missing. In the except area, is there a way to determine where the code failed?

A: 

Not cleanly. Use a default of None and test after.

try:
  username = request.REQUEST.get('username', None)
   ...
except ...:
   ...
else:
  if username is None:
     ...
Ignacio Vazquez-Abrams