我做了一个机器人,但它有时无法回答
I had made a bot but it sometimes fails to answer
这个机器人是为像人一样聊天而设计的,它使用一个端点,它工作得很好,但有时。
我尽力解决了还是报错
我未修改的代码
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()
这个机器人是为像人一样聊天而设计的,它使用一个端点,它工作得很好,但有时。
我尽力解决了还是报错
我未修改的代码
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()