Created
March 16, 2017 04:55
-
-
Save kehr/2ccf96844687c2b7522258fded4977c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tasks | |
import logging | |
import tornado.web | |
import functools | |
import threading | |
from tornado import gen | |
from tornado.concurrent import Future | |
from tornado.web import asynchronous | |
class Basehandler(tornado.web.RequestHandler): | |
def run(self, func, *args, **kwargs): | |
"""异步调用""" | |
# return self.thread_async(func, *args, **kwargs) | |
return self.ioloop_async(func, *args, **kwargs) | |
def ioloop_async(self, func, *args, **kwargs): | |
"""基于 IOLoop 的异步调度""" | |
future = Future() | |
@functools.wraps(func) | |
def _wrapper(*args, **kwargs): | |
try: | |
result = func(*args, **kwargs) | |
if isinstance(result, Future): | |
result = result.result() | |
except Exception as e: | |
result = None | |
future.set_exception(e) | |
future.set_result(result) | |
tornado.ioloop.IOLoop.current().add_callback(functools.partial(_wrapper, *args, **kwargs)) | |
return future | |
def thread_async(self, func, *args, **keywords): | |
"""基于线程的异步调用""" | |
future = Future() | |
@functools.wraps(func) | |
def _wrapper(): | |
try: | |
result = func(*args, **keywords) | |
# 如果异步调用中再次开了多个异步调用 | |
# 则需要解析多个异步调用的 Future 结果 | |
if isinstance(result, Future): | |
result = result.result() | |
future.set_result(result) | |
except Exception as e: | |
future.set_exception(e) | |
logging.exception(e) | |
t = threading.Thread(target=_wrapper) | |
t.daemon = True | |
t.start() | |
return future |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment