Reputation: 53
I made a code but it gives error unable to close a running loop
Code is
import aiohttp
import asyncio
async def get_response(query):
async with aiohttp.ClientSession() as ses:
async with ses.get(
f'https://some-random-api.ml/chatbot?message={query}'
) as resp:
return (await resp.json()),['response']
#using an event loop
loop = asyncio.get_event_loop()
Task = asyncio.gather(*[get_response('world') for _ in range(500)])
try:
loop.run_until_complete(Task)
finally:
loop.close()
Please modify the code for me because I'm a newly developer
I will be highly obliged if you help me out
Upvotes: 0
Views: 107
Reputation: 39546
Here's fully working example:
import aiohttp
import asyncio
_sem = None
async def get_response(query):
async with _sem:
async with aiohttp.ClientSession() as ses:
async with ses.get(f'http://httpbin.org/get?test={query}') as resp:
return (await resp.json())['args']
async def main():
global _sem
_sem = asyncio.Semaphore(10) # read https://stackoverflow.com/q/48483348/1113207
return await asyncio.gather(*[get_response(i) for i in range(20)])
res = asyncio.run(main())
print(res)
Upvotes: 1
Reputation: 32123
I would recommend to use the asyncio.run()
function to run the top-level entry point main()
function:
import aiohttp
import asyncio
async def get_response(query):
async with aiohttp.ClientSession() as ses:
async with ses.get(
f'https://httpbin.org/json'
) as resp:
return (await resp.json()), ['response']
async def main():
res = await asyncio.gather(*[get_response('world') for _ in range(500)])
asyncio.run(main())
Upvotes: 0