【问题标题】:In my python code i get the error 'await' outside function在我的 python 代码中,我收到错误“等待”外部函数
【发布时间】:2021-02-09 16:50:43
【问题描述】:

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

但我收到此错误 文件“/app/chatbot/plugins/response.py”,第 10 行 打印((等待get_response('世界'))) ^ SyntaxError: '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')))

【问题讨论】:

  • 最后一行使用await outsideasync 函数。你不能这样做。
  • 我该如何解决??

标签: python python-3.x aiohttp


【解决方案1】:

解决方案:

await 用于async 函数/方法以等待其他异步任务,但如果您在async 函数/方法之外调用async 函数/方法,则需要使用@987654325 @方法调用异步函数/方法

这里是完整的解决方案:

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

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多