tornado 异步化以及协程化

异步化:

import tornado.web
import tornado.ioloop
import tornado.httpclient

class MainHandler(tornado.web.RequestHandler):

    @tornado.web.asynchorous    #装饰器定义get函数,get返回不需要等到访问结束,但是也无法发送response给客户端,只有当指定函数中的finish函数被调用时证明response生成工作已经完成了!
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_client.fetch('http://www.baidu.com',callback=self.on_response)

    def on_response(self,response):
        
        self.write(response)
        self.finish()  #response生成

异步化提高并发能力,但是代码显得繁琐

协程化:

import tornado.web
import tornado.httpclient
import tornado.ioloop
import tornado.gen

class MainHandler(tornado.web.RequestHandler):

    @tornado.gen.coroutine
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        response = yield http.fetch('http://www.baidu.com')
        self.write(response)

装饰器gen.coroutine证明该函数是一个协程函数,只需用yield关键字调用其他阻塞函数即可,如fetch函数,不会阻塞协程的继续执行实现并发,也可以通过线程池建立两个线程实现并发!

猜你喜欢

转载自blog.csdn.net/weixin_42694291/article/details/83865211