-->

Dispatching from one webapp2.RequestHandler to ano

2019-07-23 18:39发布

问题:

Is there a way to internally pass on the handling of a request from one RequestHandler subclass to another? Basically, what I would like to do is, from the get method of a RequestHandler (well, a subclass of RequestHandler), dispatch the task of handling the request to another handler (subclass of RequestHandler), whose name is determined by a value fetched from the datastore (I'm using GAE, but that is irrelevant to this problem). The code would look something like this:

class Dispatcher(RequestHandler):
    def get_handler(some_id):
        handler_name = get_handler_name(some_id) # fetches from datastore/etc.
        return getattr(my_module, handler_name)

    def get(self, some_id, *args, **kwargs):
        handler = get_handler(some_id) # e.g., handler could be a HandlerA

        # Not a real function, just to describe what to do:
        # invokes get method of HandlerA (if handler == HandlerA)
        dispatch_to_handler(handler, self, *args, **kwargs) 

    def post(self, some_id):
        handler = get_handler(some_id)

        dispatch_to_handler(....) # dispatches to post method of the handler


class HandlerA(RequestHandler):
    def get(self, *args, **kwargs):
        do_stuff()

    def post(...):
        do_post_stuff()

The big issue is that I need to somehow pass self and the positional and keyword arguments on to the other handler (HandlerA in this example), as self contains the request, response, session, authentication, and other data, which HandlerA (or whatever the handler may be) needs in order to process the request.

回答1:

Try it this way:

def get(self, some_id, *args, **kwargs)
    handler_cls = get_handler(some_id)
    handler = handler_cls(self.request, self.response)
    return handler.dispatch()