Skip to content

Integration with tornado (python)

Dustin Spicuzza edited this page Aug 25, 2016 · 1 revision

The future-like objects returned by gRPC are not currently compatible with tornado, so you need to wrap them in order to use it. Here's a code sample that does the trick (tested with tornado 4.4 and grpcio 1.0.0):

from tornado.ioloop import IOLoop
from tornado.gen import Future

def _fwrap(f, gf):
    try:
        f.set_result(gf.result())
    except Exception as e:
        f.set_exception(e)

def fwrap(gf, ioloop=None):
    '''
        Wraps a GRPC result in a future that can be yielded by tornado
        
        Usage::
        
            @coroutine
            def my_fn(param):
                result = yield fwrap(stub.function_name.future(param, timeout))
        
    '''
    f = Future()

    if ioloop is None:
        ioloop = IOLoop.current()

    gf.add_done_callback(lambda _: ioloop.add_callback(_fwrap, f, gf))
    return f
Clone this wiki locally