Dispatching from one webapp2.RequestHandler to another

廉价感情. 提交于 2019-12-11 08:14:34

问题


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()


来源:https://stackoverflow.com/questions/14788806/dispatching-from-one-webapp2-requesthandler-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!