How do I make handlers automatically .decode('

2019-08-02 02:52发布

问题:

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.

回答1:

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.



回答2:

One way to do this is with a decorator. It's not entirely automatic, but it's also more explicit:

def decode_utf8(inner):
  def func(self, *args, **kwargs):
    args = [x.decode('utf8') for x in args]
    kwargs = dict((k, v.decode('utf8')) for k, v in kwargs.items())
    return inner(self, *args, **kwargs)
  return func

Then, just use this to decorate any methods you want to decode the arguments for:

class MyHandler(webapp2.RequestHandler):
  @decode_utf8
  def get(self, foo, bar):
    #...