0

У меня есть асинхронная функция, которая выполняет запросы к market.csgo.com по API. Все работает исправно и считает правильно, но проблема в конечном print. Мой код:

import asyncio
import aiohttp

user_input = input('Enter: sell ')

sale_total_sum = 0
amount_total_items = 0

async def get_on_sale(session, dictt):
    global sale_total_sum 
    global amount_total_items

    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

            print(f'Nick: {dictt[0]} Items each sum: {each_sale_sum} amount: {each_amount_items}')

        print(f'Total sale sum: {round(sale_total_sum/100*95)} 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())

Я получаю:

Nick: acc1 Items each sum: 100
Total sale sum: 100 Items total: 1
Nick: acc2 Items each sum: 200
Total sale sum: 300 Items total: 2
Nick: acc3 Items each sum: 300
Total sale sum: 600 Items total: 3
Nick: acc4 Items each sum: 400
Total sale sum: 1000 Items total: 4
Nick: acc5 Items each sum: 500
Total sale sum: 1500 Items total: 5

Мне нужно:

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

Я пытался смещать print(f'Total sale sum: {round(sale_total_sum/100*95)} Items total: {amount_total_items}') Но он всеравно выводит на каждом запросе. Возможно есть способ дождаться выполения всех асинхронных запросов и вывести print корректно?

2
  • 1
    Ну выводите "Total sale" в функции Main после await asyncio.gather(*tasks). await asyncio.gather - это и есть "дождаться выполнения всех асинхронных запросов" (и собрать из результаты в список)
    – insolor
    28 июл 2022 в 12:08
  • @insolor Спасибо, все заработало, почему я сам до этого не додумался. 28 июл 2022 в 12:10

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.