2

I'm using Python asyncio to implement a fast http client.

As you can see in the comments below inside the worker function I get the responses as soon as they are finished. I would like to get the responses ordered and this is why I'm using asyncio.gather.

Why is it returning None? Can anybody help?

Thank you so much!

import time
import aiohttp
import asyncio

MAXREQ = 100
MAXTHREAD = 500
URL = 'https://google.com'
g_thread_limit = asyncio.Semaphore(MAXTHREAD)


async def worker(session):
    async with session.get(URL) as response:
        await response.read()   #If I print this line I get the responses correctly

async def run(worker, *argv):
    async with g_thread_limit:
        await worker(*argv)

async def main():
    async with aiohttp.ClientSession() as session:
        await asyncio.gather(*[run(worker, session) for _ in range(MAXREQ)])

if __name__ == '__main__':
    totaltime = time.time()
    print(asyncio.get_event_loop().run_until_complete(main()))   #I'm getting a None here
    print (time.time() - totaltime)

1 Answer 1

2

Your function run doesn't return nothing explicitly, so it returns None implicitly. Add return statement and you'll get a result

async def worker(session):
    async with session.get(URL) as response:
        return await response.read()


async def run(worker, *argv):
    async with g_thread_limit:
        return await worker(*argv)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.