Search code examples
pythonasync-awaitpython-asyncio

How to sum the result of async requests?


I have an async function that returns a number (int) to me on each request, how do I add it up and print it correct to the console?

async def get_on_sale(session, dictt):
    data = {}
    sale_total_sum = 0
    amount_total_items = 0

    async with session.get(f'https://market.csgo.com/api/v2/items?key={dictt[1][1]}') as resp:
        html = await resp.json()
        
        if html['items'] is None:
            pass
        else:
            each_sale_sum = 0
            each_amount_items = 0
            
            for i in html['items']:
                sale_total_sum += i['price']
                each_sale_sum += i['price']
                each_amount_items += 1
                amount_total_items += 1
            
            key = dictt[0]
            value = dictt[1][0]
            data.setdefault(key, [])
            data[key].append(value)
            data[key].append(each_sale_sum)
            data[key].append(each_amount_items)

    for key, value in data.items():
        print(f'Nick: {key} Items each sum: {each_sale_sum}')
    print(f'Total sale sum: {sale_total_sum} Items total: {amount_total_items}')


async def Main():
    profiles = users()
    async with aiohttp.ClientSession(trust_env=True) as session:
        tasks = []
        if user_input == 'sell':
            for i in profiles.items():
                task = asyncio.ensure_future(get_on_sale(session, i))
                tasks.append(task)
            await asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
loop.run_until_complete(Main())

I get:

Nick: acc1 Items each sum: 100
Total sale sum: 100 Items total: 1
Nick: acc2 Items each sum: 200
Total sale sum: 200 Items total: 1
Nick: acc3 Items each sum: 300
Total sale sum: 300 Items total: 1
Nick: acc4 Items each sum: 400
Total sale sum: 400 Items total: 1
Nick: acc5 Items each sum: 500
Total sale sum: 500 Items total: 1

I need:

Nick: acc1 Items each sum: 100
Nick: acc2 Items each sum: 200
Nick: acc3 Items each sum: 300
Nick: acc4 Items each sum: 400
Nick: acc5 Items each sum: 500
Total sale sum: 1500 Items total: 5

My problem is that the variable sale_total_sum = 0 considers the amount only within one account, and not all together


Solution

  • You are basically overwriting the variables as they are declared locally inside the function. To solve this:

    Declare the following variables outside the function and make them global by using global keyword.

    data = {}
    sale_total_sum = 0
    amount_total_items = 0
    
    async def get_on_sale(session, dictt):
        global data = {}
        global sale_total_sum = 0
        global amount_total_items = 0
        ...
        ...
    
    

    Remove the for loop at the end of the function and just print the below:

        ...
        ...
        print(f'Nick: {key} Items each sum: {each_sale_sum}')
    

    At the end of the program, print the last line of the current function:

       ...
       ...
       print(f'Total sale sum: {sale_total_sum} Items total: {amount_total_items}')