Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/sync_client.py
1240 views
1
"""
2
Synchronous client to retrieve web pages.
3
"""
4
5
from urllib.request import urlopen
6
import time
7
8
ENCODING = 'ISO-8859-1'
9
10
11
def get_encoding(http_response):
12
"""Find out encoding."""
13
content_type = http_response.getheader("Content-type")
14
for entry in content_type.split(";"):
15
if entry.strip().startswith('charset'):
16
return entry.split('=')[1].strip()
17
return ENCODING
18
19
20
def get_page(host, port, wait=0):
21
"""Get one page suppling 'wait' time.
22
23
The path will be build with 'host:port/wait'
24
"""
25
full_url = '{}:{}/{}'.format(host, port, wait)
26
with urlopen(full_url) as http_response:
27
html = http_response.read().decode(get_encoding(http_response))
28
return html
29
30
31
def get_multiple_pages(host, port, waits, show_time=True):
32
"""Get multiple pages."""
33
34
start = time.perf_counter()
35
pages = [get_page(host, port, wait) for wait in waits]
36
duration = time.perf_counter() - start
37
sum_waits = sum(waits)
38
39
if show_time:
40
msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
41
print((msg.format(duration, sum_waits)))
42
43
return pages
44
45
if __name__ == '__main__':
46
47
def main():
48
"""Test it."""
49
pages = get_multiple_pages(
50
host='http://localhost',
51
port='8888',
52
waits=[1, 5, 3, 2])
53
for page in pages:
54
print(page)
55
56
main()
57
58
59