Skip to content

Instantly share code, notes, and snippets.

@richarddun
Last active September 1, 2017 19:24
Show Gist options
  • Save richarddun/d243963f6ae9c966f031030631ab8717 to your computer and use it in GitHub Desktop.
Save richarddun/d243963f6ae9c966f031030631ab8717 to your computer and use it in GitHub Desktop.
Sample usage of aiohttp to post arbitary data and return / use the result in original order with asyncio.gather()
import asyncio
import aiohttp
import json
async def retrieve_data(postdata):
async with aiohttp.ClientSession() as client:
#use the excellent httpbin.org as a springboard
postrep = await client.post('http://httpbin.org/post',data={"postkey":postdata})
jsonobj = json.loads(await postrep.text())
return jsonobj['form']['postkey']
def main():
puntlist = [x for x in range(11)] # arbitrary range
loop = asyncio.get_event_loop()
tasks = [retrieve_data(x) for x in puntlist] #build a list of tasks
returned = loop.run_until_complete(asyncio.gather(*tasks)) #shunt them through the loop
for i in returned:
print(i)
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment