首页 > 解决方案 > 我的代码说它无法关闭正在运行的循环

问题描述

我做了一个代码,但它给出了错误,无法关闭正在运行的循环

代码是

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()

请为我修改代码,因为我是新开发人员

如果你能帮助我,我将非常感激

标签: python-3.xpython-asyncioaiohttp

解决方案


这是完整的工作示例:

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)

推荐阅读