Description
When looking at aiohttp README, the hello word looks like that:
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())For requests, it looks like this:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json
{u'private_gists': 419, u'total_private_repos': 77, ...}I can see three issues with the way aiohttp present itself:
- The snippet seems to have unnecessary complexity
- The snippet doesn't feature any quick scripting setup
- There is no explanation for the necessary complexity
Expected behaviour
First, extra complexity should be removed. I understand the benefit of if __name__ == "__main__", but in a hello word type of code, it's noise that makes the code seems bigger than necessary. If you have the skill to learn async, you know when to add it later.
Also, can the code go from:
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)To:
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
return await response.text()?
I'm guessing the first form exhibit some kind of best practice I'm missing but:
- since I'm missing it, I have no way to understand why it's best, and won't use it in the future
- it makes the code feels heavy, and hide the expressiveness of aiohttop behind the verbosity of the coroutine system
- the first time you grab for aiohttp, you probably just want to make a quick script out of it, not build a system with best practices
And lastly, even this is weird:
async def main():
async with aiohttp.ClientSession() as session: # why session ?
async with session.get('http://python.org') as response: # why can't I do that in one line ?
return await response.text()This is necessary complexity. It's done for a reason, but coming from requests, it's strange and seems uncalled for. The README should acknowledge that, then offer a link leading to and explanation of why this is necessary for an async lib, and the consequences of it. It there are shortcuts to that syntax for quick scripts with less performance/best practice needs, the README should mention THAT first, give a quick warning, then follow with the best practice.
aiohttp is the requests of async as for now. It's the first face a newcommer see when discovering the async world nowaday (well, after playing with asyncio.sleep in tutorials).