RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1265917
Accepted
piece0f
piece0f
Asked:2022-04-04 18:11:33 +0000 UTC2022-04-04 18:11:33 +0000 UTC 2022-04-04 18:11:33 +0000 UTC

lru_cache 和清除缓存

  • 772

有一个电报机器人根据时间表发送报价。添加到其lru_cache通过functools.

结果,用户收到了 3 次相同的报价(在不同的时间),尽管cache_clear()我在每次邮寄后都收到了。引号取自 MongoDB,这是我想要缓存的时刻,这样它就不会花一秒钟的时间。

class Quote:
    @lru_cache(maxsize=19)
    def check(self, user: str, check=True) -> dict:
        """Checks for quote available for {user}"""
        est_quotes = self.db.estimated_document_count()
        if self.db.count_documents({"Users": user}) >= est_quotes - 1:
            # removes user id from DB if there is no more available quotes for user
            self.db.update_many({"Users": user}, {"$pull": {"Users": user}})
        all_quotes = self.db.find({})
        while True:
            quote = all_quotes[random.randint(0, est_quotes - 1)]
            if not check:
                # if check for available is not required return random quote
                return quote
            if user in quote["Users"]:
                continue
            required_quote = quote
            self.db.update_one({"Quote": quote["Quote"]}, {"$push": {"Users": user}})
            return required_quote

    def random(self, user, checking=False):
        """ Sends random quote for user.
            If checking == False, it does not check for the presence of id in the database.
        """
        quo = self.check(user, check=checking)
        keyboard = types.InlineKeyboardMarkup()
        key_book = types.InlineKeyboardButton(text='📖', callback_data='book', url=quo["URL"])
        keyboard.add(key_book)
        #   key_like = types.InlineKeyboardButton(text='Нет', callback_data='no')
        #   keyboard.add(key_like)
        bot.send_message(user,
                         text=f'<i>{quo["Quote"]}\n</i>\n<b>{quo["Book"]}</b>\n#{quo["Author"]}',
                         parse_mode='HTML', reply_markup=keyboard)

    def randoms(self, group: int):
        """Sends random quote for users who aren't in 'stopped' list"""
        start_time = time.time()
        counter = 0
        with open(f'users{group}', 'r') as users_r:
            r = users_r.read().splitlines()
        print("=================================")
        for user_id in r:
            if user_id in self.stopped:
                continue
            try:
                self.random(str(user_id), True)
                print(f"Latency #{counter}: {str(time.time() - start_time)[:4]} seconds")
            except telebot.apihelper.ApiTelegramException as e:
                print(f"Bad ID ({user_id}):", e)
            except Exception as e:
                print(e)
            finally:
                counter += 1
        self.check.cache_clear()

很可能,我只是不太了解缓存的方式和内容,但我请您为我的问题提出最佳解决方案。

python
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    MaxU - stop genocide of UA
    2022-04-04T18:53:45Z2022-04-04T18:53:45Z

    缓存装饰器functools的目的是在使用相同参数调用装饰函数时从缓存中返回相同的结果。

    那些。在您的情况下,如果我们.check(user="user1")使用相同的参数值连续调用该方法 18 次user,那么我们将获得18 次相同的结果。

    在我看来,这显然违背了您的意图,并且lru_cache在您的情况下是错误的工具。

    PS 通常缓存装饰器用于确定性函数,但不适用于返回随机结果的函数。

    • 4

相关问题

  • 是否可以以某种方式自定义 QTabWidget?

  • telebot.anihelper.ApiException 错误

  • Python。检查一个数字是否是 3 的幂。输出 无

  • 解析多个响应

  • 交换两个数组的元素,以便它们的新内容也反转

Sidebar

Stats

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

    表格填充不起作用

    • 2 个回答
  • Marko Smith

    提示 50/50,有两个,其中一个是正确的

    • 1 个回答
  • Marko Smith

    在 PyQt5 中停止进程

    • 1 个回答
  • Marko Smith

    我的脚本不工作

    • 1 个回答
  • Marko Smith

    在文本文件中写入和读取列表

    • 2 个回答
  • Marko Smith

    如何像屏幕截图中那样并排排列这些块?

    • 1 个回答
  • Marko Smith

    确定文本文件中每一行的字符数

    • 2 个回答
  • Marko Smith

    将接口对象传递给 JAVA 构造函数

    • 1 个回答
  • Marko Smith

    正确更新数据库中的数据

    • 1 个回答
  • Marko Smith

    Python解析不是css

    • 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