Path: blob/master/languages/python/asyncio_examples/get_onepage_async.py
1240 views
"""1Get a web page asynchronously.2"""34import asyncio5import random6import time78from contextlib import closing910ENCODING = "ISO-8859-1"111213def get_encoding(header):14"""File out encoding."""15for line in header:16if line.lstrip().startswith("Content-type"):17for entry in line.split(";"):18if entry.strip().startswith('charset'):19return entry.split('=')[1].strip()20return ENCODING212223async def get_page(host, port, wait=0):24"""Get a web-page asynchronously."""25reader, writer = await asyncio.open_connection(host, port)26writer.write(27b'\r\n'.join([28'GET /{} HTTP/1.0'.format(wait).encode(ENCODING),29b'Host: %b' % host.encode(ENCODING),30b'Connection: close',31b'',32b'']))33header = []34msg_lines = []35async for raw_line in reader:36line = raw_line.decode(ENCODING).strip()37if not line.strip():38break39header.append(line)40encoding = get_encoding(header)41async for raw_line in reader:42line = raw_line.decode(encoding).strip()43msg_lines.append(line)44writer.close()45return "\n".join(msg_lines)464748def get_multiple_pages(host, port, waits, show_time=True):49"""Get multiple pages."""50start = time.perf_counter()51pages = []52with closing(asyncio.get_event_loop()) as loop:53for wait in waits:54pages.append(loop.run_until_complete(get_page(host, port,wait)))55duration = time.perf_counter() - start56sum_waits = sum(waits)57if show_time:58msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."59print((msg.format(duration, sum_waits)))6061return pages626364def get_multiple_pages2(host, port, waits, show_time=True):65"""Get multiple pages."""66start = time.perf_counter()67pages = []68tasks = []6970with closing(asyncio.get_event_loop()) as loop:71for wait in waits:72tasks.append(get_page(host, port, wait))73pages = loop.run_until_complete(asyncio.gather(*tasks))7475duration = time.perf_counter() - start76sum_waits = sum(waits)7778if show_time:79msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."80print((msg.format(duration, sum_waits)))8182return pages838485if __name__ == '__main__':8687def main():88"""Test it!"""89if random.choice([True, False]):90pages = get_multiple_pages(host='localhost', port='8888',waits=[1, 5, 3, 2])91for page in pages:92print(page)93else:94pages = get_multiple_pages2(host='localhost', port='8888',waits=[1, 5, 3, 2])95for page in pages:96print(page)9798main()99100101102