2021-08-16

tornado异步和同步交叉使用

1 同步代码异步执行

from concurrent.futures.thread import ThreadPoolExecutor

class AsyncClient(object):
    __instance = None
    """
        这里做成了单例以便于使用相同线程池来处理所有这种情况
    """
    
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(
                AsyncClient, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        self.executor = ThreadPoolExecutor()
        self.io_loop = ioloop.IOLoop.current()

    @concurrent.run_on_executor
    def methods(self, syncfunc, args):
        return syncfunc(args)

class AsyncRequestHandle(tornado.web.RequestHandler):
    async def get(self):
        client = AsyncClient()
        res = await client.methods(requests.get,"https://www.baidu.com")
        print(res.status_code)
        self.write('ok')
        await self.finish()


2 同步代码中引入异步代码时

alt_ioloop_fut = concurrent.futures.Future()
def run_alt_loop():
    asyncio.set_event_loop(asyncio.SelectorEventLoop())
    ioloop = IOLoop()
    alt_ioloop_fut.set_result(ioloop)
    ioloop.start()
alt_thread = threading.Thread(target=run_alt_loop)
alt_thread.daemon = True
alt_thread.start()
alt_ioloop = alt_ioloop_fut.result()

def run_coro_on_other_thread(f, *args, **kw):
    fut = concurrent.futures.Future()
    async def wrapper():
        try:
            res = await f(*args, **kw)
            fut.set_result(res)
        except Exception as e:
            fut.set_exception(e)
    alt_ioloop.add_callback(wrapper)
    return fut.result()

async def func():
    async_client = httpclient.AsyncHTTPClient()
    res = await async_client.fetch('https://www.baidu.com')
    return res

class Handler(tornado.web.RequestHandler):
    def get(self):
        res = run_coro_on_other_thread(func)
        print(res.body)
        self.write('ok')

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.只要一个物种的出生率大于死亡率,它就可以延续下去。人类基因的多样性,是对抗所有已知和未知灾难的终极武器。 2....
    yyhanna阅读 7,166评论 0 1
  • 中医巧治耳鸣耳聋_真实的经验分享? 耳鸣就是自觉耳内有各种各样的声音,如流水声,嗡嗡声,蝉鸣声等,可时响不停,或持...
    耳鸣小贴士88阅读 1,202评论 0 0
  • 布尔表达式 布尔值 • 用于表示判断中的是与否,一般用于条件测试中; • 取值只有 True 、False ; 逻...
    霸业阅读 2,738评论 0 0
  • 我的暑假我做主 三5班:戎静茹 暑假已经开始了,当我正在脑海里想着怎么度过这个愉快的暑假时,...
    崔欣欣cxx阅读 1,468评论 0 2
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 11,308评论 0 4

友情链接更多精彩内容