Python 我制作了一个机器人,但它有时无法响应
这个机器人是为像人类一样聊天而设计的,它使用一个端点,它工作得很好,但有时也会 我尽了最大的努力去解决它,但它仍然会出错 我的未修改代码Python 我制作了一个机器人,但它有时无法响应,python,python-3.x,python-asyncio,aiohttp,Python,Python 3.x,Python Asyncio,Aiohttp,这个机器人是为像人类一样聊天而设计的,它使用一个端点,它工作得很好,但有时也会 我尽了最大的努力去解决它,但它仍然会出错 我的未修改代码 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/cha
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']
async def main():
print(await get_response('world'))
但它会产生错误
rep = await get_response(query)
File "/app/chatbot/plugins/response.py", line 9, in get_response
return (await resp.json())['response']
KeyError: 'response'
您应该使用asycio.gather来收集任务,这将使您的代码对垃圾邮件具有适应性
gather
允许您同时启动一组协同路由,一旦所有协同路由完成,当前上下文将恢复
以下是修复方法:
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()
让我们。