tornado 异步

一、同步和异步的区别

超市排队买东西的情况,排在你前面的人没有结算完成时,你就得等着,无法付账。

在计算机中也有类似的情形,一个程序在执行之前,需要等待其他的程序执行完成。

(一).同步

按来的顺序,一个一个处理

直观感受 :就是需要等候,效率低下

(一).异步

不考虑顺序,来了就处理

直观感受:不用等了,效率高

 

二、阻塞和非阻塞

最常见的问题,因为JS的原因,导致网页一直处于加载中,感觉网页很卡。或者电脑硬件性能不够时,电脑变卡。

做网站时,比较常见的阻塞就是:当同时有多个请求发送过来时,而且每个数据量都比较大的时候,就很容易发生阻塞。

 

三、异步编程

tornado官方推荐使用协程实现异步

(一).导包

import tornado.gen

(二).编写一个Handler

import tornado.gen


class GenHandler(BaseHandler):
    """通过协程实现的异步"""

    @tornado.web.asynchronous
    @tornado.gen.coroutine  # coroutine 协程
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(client.fetch, "http://127.0.0.1:8000/sync")  # 通过 yield 实现异步,必须使用 yield 返回
        self.write(response.body)
View Code

(三).添加路由

 

四、通过协程实现异步(自定义函数)

import tornado.gen


class FuncHandler(BaseHandler):
    """通过协程实现的异步"""

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield self.func()  # 必须使用yield
        print(response)
        self.write(response.body)

    @tornado.gen.coroutine
    def func(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(client.fetch, "http://127.0.0.1:8000/sync")
        raise tornado.gen.Return(response)
View Code

 

五、通过回调函数来实现异步

import tornado.httpclient

class CallbackHandler(BaseHandler):
    @tornado.web.asynchronous
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()  # 异步的方法
        client.fetch("http://127.0.0.1:8000/sync", callback=self.on_response)
        self.write('Ok!' + '<br>')

    def on_response(self, response):
        self.write(response.body)
        self.finish()  # 注意一定要加上
View Code

  

六、通过协程来实现异步(使用requests模块)

(一).安装所需模块

pip install futures

pip install requests

(二).导入模块

from tornado.concurrent import run_on_executor

from concurrent.futures import ThreadPoolExecutor

import requests

(三).编写代码

class MyFuncHandler(BaseHandler):
    executor = ThreadPoolExecutor()

    @tornado.web.asynchronous
    @tornado.gen.coroutine  # coroutine 协程
    def get(self):
        response = yield self.func()
        print(response)
        self.write(response.text)

    @run_on_executor
    def func(self):
        response = requests.get("http://127.0.0.1:8000/sync")
        return response
View Code

 

posted @ 2018-09-09 17:03  root01_barry  阅读(155)  评论(0编辑  收藏  举报