Socket

 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import random
class DumpDBSocket:
def is_ready(self):
return random.randrange(10) > 7
def read_data(self):
return dict(
id=1,
username='John Doe',
email='john.doe@gmail.com'
)
class DumpHttpSocket:
def is_ready(self):
return random.randrange(10) > 5
def read_data(self):
res = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello!
</body>
</html>
"""
return res
def db():
'From external db library'
async_socket = DumpDBSocket()
while True:
if async_socket.is_ready():
return async_socket.read_data()
else:
yield
def http_get():
async_socket = DumpHttpSocket()
while True:
if async_socket.is_ready():
return async_socket.read_data()
else:
yield
def ok():
res = yield from db()
print(res)
res = yield from http_get()
print(res)
def first():
for x in range(10):
print('first:',x)
yield
class Eventloop:
coroutines = []
def run(self):
while True:
if len(self.coroutines) == 0:
break
for coro in self.coroutines:
try:
next(coro)
except StopIteration as e:
print(coro, 'is end.')
self.coroutines.remove(coro)
def add_coroutine(self, coro):
self.coroutines.append(coro())
loop = Eventloop()
loop.add_coroutine(ok)
loop.add_coroutine(first)
if __name__ == '__main__':
loop.run()