Tornado Handler Call
Characteristics
Calling methods in other tornado handler in a single tornado request, such as the Run method
Introduction
In the background development, sometimes need to do some of the functions of integration, such as the request for the completion of a single function, and now there is a demand, need to complete these three functions, if the request logic in handler and functional logic separation is very clear (ideal state), it is convenient to invoke the function logic directly, But perhaps for a variety of reasons, handler is likely to have a lot of code that involves functional logic. Only transparent to the user, but also can be implemented by the client (for example, three requests). However, there may be other features that follow, as well as network latency issues, so the final confirmation is done in the background.
Note
There are methods to construct requests in flask, but they are not available in Tornado and need to be implemented by themselves
Achieve goals
Implement a method that passes in the handler class that needs to be called, handler inputs, and some other parameters that are required by the called function in the Hanlder, returning the result of the operation of the handler call
Implementation ideas
The true invocation of hander involves considerable preparation, error handling, and finishing. But the essence of the method in handler is the function, so as long as we can provide the data required for this function operation, it will be able to operate normally. Because Python is a runtime language, we don't need to take care of the data that we need for a method that we don't need to call in handler as a real hander. We can use rewriting to avoid the data necessary for these real handler.
Example
@coroutinedef doFakeHandle(handler, inputs,game, application): class FakeHandle(handler): def __init__(self, inputs, application, game): self.application = application self._game = game self.input = inputs self.write_list={} @property def game(self): return self._game def write(self, chunk): self.write_list.update(chunk) handler = FakeHandle(inputs, application, game) try: yield handler.run() except Exception, e: if not isinstance(e, Return): raise e raise Return(handler.write_list)
Attention
- The invocation of the method in handler needs to be specific to the specific project, the above example does not address the general situation, you can consider using **kwargs to achieve a more general approach to specific projects
- The call to the handler method may involve import issues, and one solution is to put the import statement in the function that calls Dofakehandle