Skip to content

Commit

Permalink
Retrieve four things from the web with concurrency
Browse files Browse the repository at this point in the history
Add a simple example to show how to create a client that gathers multiple web resources _concurrently_ .

I am not sure if this example is serial or concurrent.  :-(  If it is serial then it would be quite helpful for readers to understand how to make it concurrent.
  • Loading branch information
cclauss authored Jun 19, 2016
1 parent 65d385e commit 358269c
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,31 @@ To retrieve something from the web:
print(html)
To retrieve four things from the web with concurrency:

.. code-block:: python
import aiohttp
import asyncio
async def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return await response.text()
URLS = '''http://python.org
http://golang.org
http://perl.org
http://ruby-lang.org'''.split()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
coroutines = [fetch(session, url) for url in URLS]
pages = [loop.run_until_complete(coroutine) for coroutine in coroutines]
for url, page in zip(URLS, pages):
print('{:>15}\n{}\n{:.100}\n'.format(url, '=' * len(url), page))
Server
^^^^^^

Expand Down

0 comments on commit 358269c

Please sign in to comment.