import requests
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.internet import reactor,task,defer
import time
#1.非阻塞
'''
def hello(name):
print("hello world! ===>" + name + "===>" + str(int(time.time())))
#添加一个循环任务 每隔10s执行一次
task1 = task.LoopingCall(hello,'ding')
task1.start(10)
reactor.callWhenRunning(hello,'yudahai') # reactor开始运行的时候,就除法hello函数
reactor.callLater(3,hello,'yuyue') #calllater 表示3s以后在除法一次
reactor.run()
'''
#2 阻塞
def hello(name):
print("hello world! ===>" + name + "===>" + str(time.ctime()))
## 1. 问题所在
def request_google():
'''会阻塞环上的下一个函数执行'''
res = requests.get('http://www.google.com')
return res
## 1.1 解决方案1,twisted 自带的httpclient由于是异步的,不会阻塞住整个reactor的运行
'''
@defer.inlineCallbacks
def request_google():
agent = Agent(reactor)
try:
# res = yield agent.request('GET','http://www.google.com',Headers({"User-agent":['Twisted Web Client Example']}),None)
res = yield agent.request(b'GET', b'http://www.google.com', Headers({b'User-Agent': [b'Twisted Web Client '
b'Example']}),
None)
except Exception as e:
print(f"error:{e}")
return
print(res)
return res
'''
reactor.callWhenRunning(hello,'yudahai')
## 1.2 使用twisted自带的线程,它访问完毕的时候,会发送一个信号给reactor,只需修改函数的调用api 为 callInThread
reactor.callInThread(request_google)
# reactor.callLater(1,request_google)
reactor.callLater(3,hello,'yuyue')
reactor.run()
#总结
'''
1. 方案一的方式,不是所有的api都有异步接口
2. 方案二,twisted中,不能大量使用线程
3. 优先使用异步库
'''
复制代码
【异步编程】 twisted库认识
猜你喜欢
转载自juejin.im/post/7017349775842361358
今日推荐
周排行