tornodo异步请求

1.访问请求异步

# 1.保证请求是异步的
class Test(tornado.web.RequestHandler):

    def get(self):
        self.write({'k1': 'v1'})

    def post(self):
        self.write({'k1': 'v1'})


@gen.coroutine
def doing():
    # time.sleep(3) #同步的时候用的,异步不起作用
    yield tornado.gen.sleep(10)
    raise tornado.gen.Return('你好')


class Test1(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        res = yield doing()
        self.write(res)

    def post(self):
        self.write({'k2': 'v2'})
测试

结果:

http://127.0.0.1:8000/test1/延迟10秒,http://127.0.0.1:8000/test/不受影响,正常访问。

2.并发执行(场景:实时前段展示,实时插入数据库)

@gen.coroutine
def doing():
    gen.sleep(2)
    raise gen.Return('年后')


class Test1(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        start = time.time()
        #并发执行
        res, res1 = yield [doing(), doing()]
        print(time.time() - start)
        self.write(res + res1)

    def post(self):
        self.write({'k2': 'v2'})
执行时间2s+
async def doing():
    await gen.sleep(2)
    return '那你还能'

class Test1(tornado.web.RequestHandler):

    async def get(self):
        start = time.time()
        #并发执行
        res, res1 = await gen.convert_yielded([doing(), doing()])
        print(time.time() - start)
        self.write(res + res1)

    def post(self):
        self.write({'k2': 'v2'})
利用3.5 async和await

await 关键字比 yield 关键字功能要少一些. 例如,在一个使用 yield 的协程中, 你可以得到Futures 列表, 你也可以使用 tornado.gen.convert_yielded 来把任何使用 yield 工作的代码转换成使用 await 的形式.

coroutine 是给Non-blocking 函数提供异步协程的方式运行,

3.线程池异步

from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor


class Test1(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor()

    @gen.coroutine
    def get(self):
        start = time.time()
        res, res1 = yield [self.doing(), self.doing()]
        print(time.time() - start)
        self.write(res + res1)

    @run_on_executor
    def doing(self):
        time.sleep(2)
        return '22'

    def post(self):
        self.write({'k2': 'v2'})
线程方法
原文地址:https://www.cnblogs.com/liuer-mihou/p/11424629.html