Search code examples
pythongoogle-app-enginewebapp2

How do I make handlers automatically .decode('utf-8') on all routed parameters?


I'm trying to make webapp2 automatically decode all routed parameters as utf-8, before they're sent to their handler's get() method. I tried to override dispatch() in a BaseHandler class that all handlers inherit from, but I only managed to read the parameters through the request object, not change them. How would I best do this to?

EDIT

My bad, this is not about traditional GET-parameters, but rather the routed parts of the URL that the handler's get() method recieve as keyword arguments. When they contain unicode characters from the URL that was matched, they must be .decode('utf-8') or they will give an UnicodeDecodeError. I want to avoid having to do these decodes manually for every handler and routed parameter in my system.


Solution

  • This is the solution I settled for as the decoding is handled completely automatically.

    Override the dispatch() method of your base handler class that your other handlers inherit from and add the following code to it:

    route_kwargs_decoded = {}
    for key, value in self.request.route_kwargs.iteritems():
        route_kwargs_decoded[key] = value.decode('utf-8')
    self.request.route_kwargs = route_kwargs_decoded
    

    For webapp2 developers, I think it might be worth considering implementing this as a feature in future webapp2 versions, as it seems like something that should be handled automatically by the framework, or at least through a setting.