import aiohttp import asyncio from queue import Queue Empty class Requ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import aiohttp
import asyncio
from queue import Queue, Empty
class Request(object):
def __init__(self, url, callback=None):
self.url = url
self.callback = callback
class Response(object):
def __init__(self, body):
self.body = body
class Reactor(object):
def __init__(self):
self.loop = asyncio.get_event_loop()
self.task_queue = Queue()
def run(self):
self.loop.run_until_complete(self.run_loop())
@asyncio.coroutine
def run_loop(self):
while True:
try:
task = self.task_queue.get(block=False)
except Empty:
pass
else:
@asyncio.coroutine
def perform_request():
print('Requesting {}'.format(task.url))
io_res = yield from aiohttp.request('get', task.url)
body = yield from io_res.text()
res = Response(
body=body,
)
if task.callback:
task.callback(task, res)
yield from perform_request()
print('sleeping')
yield from asyncio.sleep(0.1)
def add_task(self, task):
self.task_queue.put(task)
def process_response(req, res):
print('Result of request to {}'.format(req.url))
print('Response content:')
print(res.body)
def main():
reactor = Reactor()
req = Request('http://httpbin.org/ip', callback=process_response)
reactor.add_task(req)
reactor.run()
if __name__ == '__main__':
main()