Is it possible to use tornado's gen.engine and gen.Task with twisted?

前端 未结 3 573
北海茫月
北海茫月 2021-01-21 16:03

The project I am working on is all written in Tornado, but I have included a bit of Twisted to deal with asynchronous XML-RPC. I was wondering if you can use Tornado\'s gen.engi

3条回答
  •  死守一世寂寞
    2021-01-21 16:39

    You can use gen.Task with anything that takes a callback keyword argument. However, Twisted-style code usually returns a Deferred instead of taking a callback as input. You'll need to wrap the Deferred in something tornado.gen can understand (probably a Future). Something like this (untested):

    def wrap_deferred(deferred):
        # Could also use concurrent.futures.Future from the standard library,
        # but Tornado's version gives better tracebacks on python 2.
        future = tornado.concurrent.TracebackFuture()
        deferred.addCallbacks(future.set_result, future.set_exception)
        return future
    
    @gen.coroutine
    def my_coroutine(self):
        # Use wrap_deferred instead of gen.Task
        x = yield wrap_deferred(some_twisted_function())
    

提交回复
热议问题