Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve four things from the web with concurrency #938

Closed
wants to merge 3 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't these be aggregated with asyncio.gather instead?

for url, page in zip(URLS, pages):
print('{}:\n{}=\n{:.100}\n'.format(url, '=' * len(url), page))

Server
^^^^^^

Expand Down