在我的 python 代码中,我得到错误 'await' outside function

In my python code i get the error 'await' outside function

每当我尝试制作聊天机器人时 我选择使用端点

但是我得到这个错误 文件“/app/chatbot/plugins/response.py”,第 10 行 打印((等待get_response('world'))) ^ 语法错误:'await' 外部函数

请帮助我,如果你能帮助我,我将不胜感激

我的代码在哪里

import aiohttp

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']

print((await get_response('world')))

解决方案:

awaitasync functions/methods 中用于等待其他异步任务,但是如果您在 async function/method async function/method 你需要使用 asyncio.run() 方法来调用异步 function/method

完整的解决方案如下:

import aiohttp
import asyncio #to run async funtions you need to 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']

print((asyncio.run( get_response('world')))#run the async function