RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1434335
Accepted
krubsburger
krubsburger
Asked:2022-07-30 00:33:10 +0000 UTC2022-07-30 00:33:10 +0000 UTC 2022-07-30 00:33:10 +0000 UTC

如何使python asyncio全局变量无效?

  • 772

我正在编写一个个人电报机器人来收集我的market.csgo.com帐户的统计数据。该机器人的主要任务是向 API 发送异步请求并通过 Telegram 显示信息。一切正常,但问题在于全局变量,或者更确切地说,它们的计数不正确。我的功能之一的示例:

...
import asyncio
import aiohttp


sale_total_sum = 0
amount_total_items = 0

async def get_on_sale(session, dictt, message):
    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
               
            try:
                await bot.send_message(message.from_user.id,
                    f'<a href="{dictt[1][0]}">{dictt[0]}</a> : <b>{each_sale_sum} ₽</b>\nItems: <i>{each_amount_items}</i>',
                    disable_web_page_preview=True, parse_mode=types.ParseMode.HTML)
            except exceptions.RetryAfter as e:
                await asyncio.sleep(e.timeout)


@dp.message_handler(content_types=['text'])
async def Main(message):
    profiles = users()
    
    async with aiohttp.ClientSession(trust_env=True) as session:
        tasks = []
        
        if message.text == 'On Sale 💰':
            await bot.send_message(message.from_user.id, 'Information request. Wait..')
           
            for i in profiles.items():
                task = asyncio.ensure_future(get_on_sale(session, i, message))
                tasks.append(task)
            await asyncio.gather(*tasks)
            
            await bot.send_message(message.from_user.id,
                f'<b>Total on sale: {sale_total_sum} ₽\nTotal items: {amount_total_items}\nBot start at: {start}</b>',
                reply_markup=kb_client, parse_mode=types.ParseMode.HTML)


executor.start_polling(dp, skip_updates=True)

函数结果:

Account_1: 100 ₽
Items: 1
Account_2: 200 ₽
Items: 2
Account_3: 300 ₽
Items: 3
Total on sale: 600 ₽
Total items: 6

该机器人在轮询模式下工作executor.start_polling(dp, skip_updates=True)。如果在包含后第一次调用该函数async def get_on_sale,那么它的最终计数Total on sale: 600 ₽ Total items: 6将是正确的,但随后的调用会使这个数量翻倍,实际上并非如此:

Account_1: 100 ₽
Items: 1
Account_2: 200 ₽
Items: 2
Account_3: 300 ₽
Items: 3
Total on sale: 1200 ₽
Total items: 12

我知道问题出在全局变量global sale_total_sum和global amount_total_items. 但是,如果您改用简单变量,它们将被简单地覆盖,而不是按照我的需要进行汇总。因此,我想问 -有没有办法在函数结束后以某种方式重置或重新分配这些全局变量为 0?这样在下一次调用时数据将是正确的。谢谢你。

python asyncio
  • 1 1 个回答
  • 49 Views

1 个回答

  • Voted
  1. Best Answer
    Roman-Stop RU aggression in UA
    2022-07-30T01:34:30Z2022-07-30T01:34:30Z

    get_on_sale当所有函数都在一次调用中执行时,您应该拥有此数据的生命周期Main。

    创建一个包含两个字段的对象并将其作为参数传递给,get_on_sale以便多次调用此函数来更改它。完成所有调用后,使用结果:

    from dataclasses import dataclass
    
    @dataclass
    class AggregatedStats:
        sum: int = 0
        items: int = 0
    
    async def get_on_sale(session, dictt, message, stats):
    
          ...            
                for i in html['items']:
                    stats.sum += i['price']
                    each_sale_sum += i['price']
                    each_amount_items += 1
                    stats.items += 1
                   
          ...
    
    @dp.message_handler(content_types=['text'])
    async def Main(message):
        profiles = users()
        
        async with aiohttp.ClientSession(trust_env=True) as session:
            tasks = []
            
            if message.text == 'On Sale 💰':
                await bot.send_message(message.from_user.id, 'Information request. Wait..')
               
                stats = AggregatedStats()
    
                for i in profiles.items():
                    task = asyncio.ensure_future(get_on_sale(session, i, message, stats))
                    tasks.append(task)
                await asyncio.gather(*tasks)
                
                await bot.send_message(message.from_user.id,
                    f'<b>Total on sale: {stats.sum} ₽\nTotal items: {stats.items}\nBot start at: {start}</b>',
                    reply_markup=kb_client, parse_mode=types.ParseMode.HTML)
    
    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5