from tornado import ioloop, genfrom tornado.stack_context import ExceptionStackContextdef sync(fn):def wrapper(*args, **kwargs):ret = dict(val=None)def stop(*args):ret['val'] = argsioloop.IOLoop.instance().stop()def exception_callback(*args, **kwargs):print 'in exception callback'ioloop.IOLoop.instance().stop()print argsraise args[1]with ExceptionStackContext(exception_callback):kwargs['callback'] = stopfn(*args, **kwargs)ioInstance = ioloop.IOLoop.instance()ioInstance.start()return ret['val']return wrapperclass HTTPCaller(object):@gen.enginedef call(self, callback):http_client = httpclient.AsyncHTTPClient()response = yield gen.Task(http_client.fetch, "https://www.googleaaaa.com/") ## I made this wrong url in purpose.if response.error:print 'rethrow exception'response.rethrow()else:callback(response.body)
if __name__ == "__main__":
print 'calling sync test'try:print 'get sync response = '+str(sync(HTTPCaller().call)())except Exception as ex:print 'catch exception %s' % (str(ex))print 'complete sync test'