Issue
On Python Asyncio I am trying to return a value from one function to another .
So when the if statement in the end of func "check" is True the returned will value
will go the the "print" func .
async def check(i):
async with aiohttp.ClientSession() as session:
url = f'https://pokeapi.co/api/v2/pokemon/{i}'
async with session.get(url) as resp:
data = await resp.text()
if data['state'] == 'yes':
return data['state']
## how do i keeping the structre of the asyncio and pass this result to the "print" function
async def print(here should be the return of "check" funtion is there is):
print()
await asyncio.sleep(0)
async def main():
for i in range(0,5):
await asyncio.gather(check(i),
print() )
Thank You (-:
Solution
Your code is going to run everything synchronously. You need to restructure things a bit to see any value from asyncio.
async def check(i):
async with aiohttp.ClientSession() as session:
url = f'https://pokeapi.co/api/v2/pokemon/{i}'
async with session.get(url) as resp:
data = await resp.text()
if data['state'] == 'yes':
return data['state']
async def main():
aws = [check(i) for i in range(5)]
results = await asyncio.gather(*aws)
for result in results:
print(result)
This will allow your aiohttp requests to run asynchronously. Assuming print
is really just a wrapper around the builtin, you don't need it and can just use the builtin.
If, however, print
actually does something else, you should use asyncio.as_completed
instead of asyncio.gather
.
async def my_print(result):
print(result)
await asyncio.sleep(0)
async def main():
aws = [check(i) for i in range(5)]
for coro in asyncio.as_completed(aws):
result = await coro
await my_print(result)
Answered By - dirn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.