Search code examples
python-2.7restwebapp2

How to get all query params in an obj in Python WebApp2


I have a request handler that update a user. I uses **kwargs and whatever key and value are in this dict, I update those attributes of that user and save it back to the database. The client that sends these query params to the api don't use a param object and they send it in the url.

Right now, this is how I get a single variable from the url.

class UpdateUserHandler(webapp2.RequestHandler):
    def post(self):
        first_name = self.request.get('first_name')
        last_name = self.request.get('last_name')
        #And so on ...

What I want to do is get all of the params in an object becauseI do not know how many params there will be and exactly what the names of the params will be. Is there a way in python webapp2 to get all of the params that were passed in into a single param obj or dictionary?


Solution

  • You can use:

    • self.request.GET.items() to obtain a list of param name-value tuples only from the query string:

      [(u'id', u'5574236190015488'), (u'index', u'3')]
      
    • self.request.params.items() to obtain a list of param name-value tuples from both the request body and the query string:

      [(u'id', u'5574236190015488'), (u'index', u'3')]
      
    • self.request.query_string to obtain the plain query string (which you can parse yourself any way you wish):

      'id=5574236190015488&index=3'
      

    You can find more details and maybe some other alternative better fitting your usecase at: