协程代码解析

协程版本1

# 协程 版本1

import time
import threading

gen = None

def LongIo():
    def run():
        print("执行LongIo函数")
        time.sleep(5)
        try:
            global gen
            gen.send("sunck is a good man")
            print("执行完成Long函数")
        except StopIteration as e:
            pass
    threading.Thread(target=run).start()

def reqA():
    print("开始处理reA")
    res = yield LongIo()
    print("接收到longIo的响应数据:",res)


def reqB():
    print("开始处理reqB")
    time.sleep(2)
    print("结束处理reqB")

def main():

    global gen
    gen =  reqA()  # 生成一个生成器
    next(gen)   # 执行reqA

    reqB()


    while 1:
        time.sleep(0.5)
        pass


if __name__ == '__main__':
    main()

协程版本2

# 协程 版本2

import time
import threading

gen = None

def LongIo():
    def run():
        print("执行LongIo函数")
        time.sleep(5)
        try:
            global gen
            gen.send("sunck is a good man")
            print("执行完成Long函数")
        except StopIteration as e:
            pass
    threading.Thread(target=run).start()

def genCoroutine(func):
    def wrapper(*args,**kwargs):
        global gen
        gen = func(*args,**kwargs)
        next(gen)
    return wrapper



@genCoroutine   # 装饰器
def reqA():
    print("开始处理reA")
    res = yield LongIo()
    print("接收到longIo的响应数据:",res)
    print("结束处理reqA")


def reqB():
    print("开始处理reqB")
    time.sleep(2)
    print("结束处理reqB")

def main():
    """
    global gen
    gen =  reqA()  # 生成一个生成器
    next(gen)   # 执行reqA
    :return:
    """
    reqA()
    reqB()

    while 1:
        time.sleep(0.5)
        pass


if __name__ == '__main__':
    main()

协程版本3

# 协程 版本3

import time
import threading

gen = None

def LongIo():
    print("执行LongIo函数")
    time.sleep(5)
    print("执行完成Long函数")
    yield "sunck is a good man"


def genCoroutine(func):
    def wrapper(*args,**kwargs):
        gen1 = func()   # reqA的生成器
        gen2 = next(gen1)   # LongIo的生成器
        def run(g):
            res =  next(g)
            try:
                gen1.send(res)
            except StopIteration as e:
                pass

        threading.Thread(target=run,args=(gen2,)).start()

    return wrapper



@genCoroutine   # 装饰器
def reqA():
    print("开始处理reA")
    res = yield LongIo()
    print("接收到longIo的响应数据:",res)
    print("结束处理reqA")


def reqB():
    print("开始处理reqB")
    time.sleep(2)
    print("结束处理reqB")

def main():
    """
    global gen
    gen =  reqA()  # 生成一个生成器
    next(gen)   # 执行reqA
    :return:
    """
    reqA()
    reqB()


    while 1:
        time.sleep(0.5)
        pass


if __name__ == '__main__':
    main()

tornado异步

"""
tornado异步实现方式:
1、回调幻术实现异步
2、协程实现异步
"""
tornado.httpclient.AsyncHTTPClient
 - # 定义:tornado提供的异步 web 请求客户端,用来进行异步请求
 - fetch # 函数   
 		- fetch(request,callback = None- request  # 可以是一个URL
 				- request  # tornado.httpclient.HTTPRequest对象		
 		- # 用于执行一个web请求,并异步行应返回一个Tornado.HttpResponse 
 - HTTPRequest # http 请求类,该类构造函数剋接收参数
 		-# 参数	
 			- url    # 字符串类型、要访问的网址、必传
 			- medthod   # 字符串类型、HTTP请求方式
 			- headers   # 字典或HTTPHeaders(附加协议头)
 			- body    # HTTP请求体 (post 请求时用)
 
 - HTTPResponse  # http响应类
 		- # 属性
 			- code  # 状态码
 			- reason  # 状态码的描述
 			- body  # 行应数据
 			- error  # 异常
 
 - @tornado.web.asynchronous   # 不关闭通信通道

"""
回调函数实现异步
"""
import tornado.web
from tornado.web import RequestHandler
from tornado.httpclient import AsyncHTTPClient   # 异步HTTP请求客户端
import time
import json

class StudentsHandler(RequestHandler):

    def on_response(self,response):   # 回调函数,response为回调数据
        if response.error:
            self.send_error(500)
        else:
            data = json.loads(response.body)
            self.write(data)
            
        self.finish()  # 关闭通信通道
	
	#  @tornado.web.asynchronous    不关闭连接通讯的通道(此方法器6.0版本都弃用)
	@gen.coroutine   # 不关闭连接通信的通道
    def get(self,*args,**kwargs):
        # 获取所有学生的信息(耗时操作)
        url = "www.baidu.com"
        client = AsyncHTTPClient()   # 创建异步请求客户端
        client.fetch(url,self.on_response)   # 如果客户端请求发送成功,则执行回调函数on_response
        self.write("ok")


"""
协程异步
"""
# 方法1
class Students2Handler(RequestHandler):
	
	@tornado.gen.coroutine 
	def get(self,*args,**kwargs):
        # 获取所有学生的信息(耗时操作)
        url = "www.baidu.com"
        client = AsyncHTTPClient()   # 创建异步请求客户端
        res = yield client.fetch(url)   # client.fetch(url)为耗时操作
        if res.error:
        	self.send_error(500)
        else:
        	data =  json.loads(res.body)
        	self.write(data)


# 方法2
class Students3Handler(RequestHandler):

	@tornado.gen.coroutine
	def get(self,*args,**kwargs):
		res =  yield self.getData()  # 挂起耗时操作
		self.write(res)
	
	@tornado.gen.coroutine
	def getData(self):   # 耗时操作函数
	
		url = "www.baidu.com"
		
		client = AsyncHTTPClient()   # 创建异步请求客户端
        res = yield client.fetch(url)
        if res.error:
        	ret = {"ret": 0}
        else:
        	ret =  json.loads(res.body)
        raise tornado.gen.Return(ret)   # 将耗时函数拿到的数据返回
发布了50 篇原创文章 · 获赞 3 · 访问量 1797

猜你喜欢

转载自blog.csdn.net/weixin_43056654/article/details/104228400