Reejit
Reejit

Reputation: 53

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

Whenever i try to make a Chatbot I choose to use endpoint

But i get this error File "/app/chatbot/plugins/response.py", line 10 print((await get_response('world'))) ^ SyntaxError: 'await' outside function

Please help me i would be highly obliged if you help me

Where my code is

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

Upvotes: 3

Views: 4447

Answers (1)

TERMINATOR
TERMINATOR

Reputation: 1258

Solution:

await is used in an async functions/methods to wait on other asynchronous tasks, but if you are calling an async function/method outside of an async function/method you need to use asyncio.run() method to call an async function/method

Here is the full solution:

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

Upvotes: 5

Related Questions