Search code examples
pythonwebapp2simplification

Validate webapp2 request arguments are present


I am implementing a webapp2.RequestHandler for a Python App Engine application. A common operation I need to perform is to verify that all the required HTTP request arguments are present.

To accomplish this, I keep rewriting the same boilerplate over and over again:

def put(self):
    handle = self.request.get('handle')
    phone_number = self.request.get('phone_number')

    # Check that all required parameters are present.
    missing_parameter = None
    if not handle:
        missing_parameter = 'handle'
    if not phone_number:
        missing_parameter = 'phone_number'

    if missing_parameter:
        error_message = 'Missing parameter: \'%s\'.' % (missing_parameter)
        logging.warning(error_message)
        self.error(400)
        self.response.out.write(error_message)
        return

Is there a better way to do this? I assume there is some way to abuse Python's dynamic capabilities to cut down on this boiler plate. Something like:

checkArgs(self, ['handle', 'phone_number'])


Solution

  • Docs: http://webapp-improved.appspot.com/guide/request.html#post-data

    self.request.POST returns a mulidict. So it is easy to check for the arguments

    for each in ['handle', 'phone_number']:
        if each not in self.request.POST:
            # your error code here