Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/get_onepage_async.py
1240 views
1
"""
2
Get a web page asynchronously.
3
"""
4
5
import asyncio
6
import random
7
import time
8
9
from contextlib import closing
10
11
ENCODING = "ISO-8859-1"
12
13
14
def get_encoding(header):
15
"""File out encoding."""
16
for line in header:
17
if line.lstrip().startswith("Content-type"):
18
for entry in line.split(";"):
19
if entry.strip().startswith('charset'):
20
return entry.split('=')[1].strip()
21
return ENCODING
22
23
24
async def get_page(host, port, wait=0):
25
"""Get a web-page asynchronously."""
26
reader, writer = await asyncio.open_connection(host, port)
27
writer.write(
28
b'\r\n'.join([
29
'GET /{} HTTP/1.0'.format(wait).encode(ENCODING),
30
b'Host: %b' % host.encode(ENCODING),
31
b'Connection: close',
32
b'',
33
b'']))
34
header = []
35
msg_lines = []
36
async for raw_line in reader:
37
line = raw_line.decode(ENCODING).strip()
38
if not line.strip():
39
break
40
header.append(line)
41
encoding = get_encoding(header)
42
async for raw_line in reader:
43
line = raw_line.decode(encoding).strip()
44
msg_lines.append(line)
45
writer.close()
46
return "\n".join(msg_lines)
47
48
49
def get_multiple_pages(host, port, waits, show_time=True):
50
"""Get multiple pages."""
51
start = time.perf_counter()
52
pages = []
53
with closing(asyncio.get_event_loop()) as loop:
54
for wait in waits:
55
pages.append(loop.run_until_complete(get_page(host, port,wait)))
56
duration = time.perf_counter() - start
57
sum_waits = sum(waits)
58
if show_time:
59
msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
60
print((msg.format(duration, sum_waits)))
61
62
return pages
63
64
65
def get_multiple_pages2(host, port, waits, show_time=True):
66
"""Get multiple pages."""
67
start = time.perf_counter()
68
pages = []
69
tasks = []
70
71
with closing(asyncio.get_event_loop()) as loop:
72
for wait in waits:
73
tasks.append(get_page(host, port, wait))
74
pages = loop.run_until_complete(asyncio.gather(*tasks))
75
76
duration = time.perf_counter() - start
77
sum_waits = sum(waits)
78
79
if show_time:
80
msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
81
print((msg.format(duration, sum_waits)))
82
83
return pages
84
85
86
if __name__ == '__main__':
87
88
def main():
89
"""Test it!"""
90
if random.choice([True, False]):
91
pages = get_multiple_pages(host='localhost', port='8888',waits=[1, 5, 3, 2])
92
for page in pages:
93
print(page)
94
else:
95
pages = get_multiple_pages2(host='localhost', port='8888',waits=[1, 5, 3, 2])
96
for page in pages:
97
print(page)
98
99
main()
100
101
102