Created
January 9, 2019 14:45
-
-
Save mobileappconsultant/255ecfb6bfa5baae3b79db05b2fe14e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
### Concurrency .. Simple Definition: using threads to execute tasks. Simple Analogy: Imagine how frustrating it'd be or how long it'd take | |
# if there was only 1 platform | |
# at Woolwich Arsenal station and you are travelling to London Bridge. So you have to wait for the train to arrive from London Bridge | |
# and for people to disembark from the train before you get a chance to begin your journey to London Bridge. Or even simpler imagine Ade's Cash | |
# and Carry with only 1 till open and you are doing Christmas shopping.. Happens sometimes :) Python provides a construct called async/await. | |
# If a task is gonna a while then we need to "async" it. If we don't know that a function call will be immediate we need to "await" it. | |
# To use it just put it async before the word "def" and when I call my method call it with await before method name | |
async def get_html(session, url): | |
async with session.get(url, ssl=False) as res: | |
return await res.text() | |
async def main(): | |
async with aiohttp.ClientSession() as session: | |
html = await get_html(session, 'http://datascience.com') | |
print(html[: 1000]) # first 1000 characters | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment