Path: blob/master/languages/python/asyncio_examples/sync_client.py
1240 views
"""1Synchronous client to retrieve web pages.2"""34from urllib.request import urlopen5import time67ENCODING = 'ISO-8859-1'8910def get_encoding(http_response):11"""Find out encoding."""12content_type = http_response.getheader("Content-type")13for entry in content_type.split(";"):14if entry.strip().startswith('charset'):15return entry.split('=')[1].strip()16return ENCODING171819def get_page(host, port, wait=0):20"""Get one page suppling 'wait' time.2122The path will be build with 'host:port/wait'23"""24full_url = '{}:{}/{}'.format(host, port, wait)25with urlopen(full_url) as http_response:26html = http_response.read().decode(get_encoding(http_response))27return html282930def get_multiple_pages(host, port, waits, show_time=True):31"""Get multiple pages."""3233start = time.perf_counter()34pages = [get_page(host, port, wait) for wait in waits]35duration = time.perf_counter() - start36sum_waits = sum(waits)3738if show_time:39msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."40print((msg.format(duration, sum_waits)))4142return pages4344if __name__ == '__main__':4546def main():47"""Test it."""48pages = get_multiple_pages(49host='http://localhost',50port='8888',51waits=[1, 5, 3, 2])52for page in pages:53print(page)5455main()56575859