
import requests
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.internet import reactor,task,defer
import time
'''
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()
'''
def hello(name):
print("hello world! ===>" + name + "===>" + str(time.ctime()))
def request_google():
'''会阻塞环上的下一个函数执行'''
res = requests.get('http://www.google.com')
return res
'''
@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')
reactor.callInThread(request_google)
reactor.callLater(3,hello,'yuyue')
reactor.run()
'''
1. 方案一的方式,不是所有的api都有异步接口
2. 方案二,twisted中,不能大量使用线程
3. 优先使用异步库
'''