Not much has been done with asyncio, but asyncio.get_event_loop() should be what you need, you will also obviously have to change what your function takes as arguments and use asyncio.wait(tasks) according to docs :
zips = ['90210', '60647'] zip_cities = dict() @asyncio.coroutine def get_cities(zipcode): url = 'https://maps.googleapis.com/maps/api/geocode/json?key=abcdefg&address='+zipcode+'&sensor=true' fut = loop.run_in_executor(None,urllib.request.urlopen, url) response = yield from fut string = response.read().decode('utf-8') data = json.loads(string) city = data['results'][0]['address_components'][1]['long_name'] state = data['results'][0]['address_components'][3]['long_name'] zip_cities.update({idx: [zipcode, city, state]}) loop = asyncio.get_event_loop() tasks = [asyncio.async(get_cities(z, i)) for i, z in enumerate(zips)] loop.run_until_complete(asyncio.wait(tasks)) loop.close() print(zip_cities) # doesnt work {0: ['90210', 'Beverly Hills', 'California'], 1: ['60647', 'Chicago', 'Illinois']}
I don't have> = 3.4.4, so I had to use asyncio.async instead of asyncio.ensure_future
Or change the logic and create a dict from task.result from tasks:
@asyncio.coroutine def get_cities(zipcode): url = 'https://maps.googleapis.com/maps/api/geocode/json?key=abcdefg&address='+zipcode+'&sensor=true' fut = loop.run_in_executor(None,urllib.request.urlopen, url) response = yield from fut string = response.read().decode('utf-8') data = json.loads(string) city = data['results'][0]['address_components'][1]['long_name'] state = data['results'][0]['address_components'][3]['long_name'] return [zipcode, city, state] loop = asyncio.get_event_loop() tasks = [asyncio.async(get_cities(z)) for z in zips] loop.run_until_complete(asyncio.wait(tasks)) loop.close() zip_cities = {i:tsk.result() for i,tsk in enumerate(tasks)} print(zip_cities) {0: ['90210', 'Beverly Hills', 'California'], 1: ['60647', 'Chicago', 'Illinois']}
If you look at external modules, there is also a request port that works with asyncio.
Padraic cunningham
source share