Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/twitchio/cache.py
7771 views
"""1The MIT License (MIT)23Copyright (c) 2017-2021 TwitchIO45Permission is hereby granted, free of charge, to any person obtaining a6copy of this software and associated documentation files (the "Software"),7to deal in the Software without restriction, including without limitation8the rights to use, copy, modify, merge, publish, distribute, sublicense,9and/or sell copies of the Software, and to permit persons to whom the10Software is furnished to do so, subject to the following conditions:1112The above copyright notice and this permission notice shall be included in13all copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS16OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING20FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER21DEALINGS IN THE SOFTWARE.22"""2324import time25import functools26from typing import Hashable272829__all__ = ("TimedCache", "user_cache", "id_cache")303132class TimedCache(dict):33def __init__(self, seconds: int):34self.__timeout = seconds35super().__init__()3637def _verify_cache(self):38now = time.monotonic()39to_remove = [key for (key, (_, exp)) in self.items() if now > (exp + self.__timeout)]40for k in to_remove:41del self[k]4243def __getitem__(self, key):44self._verify_cache()45return super().__getitem__(key)[0]4647def __setitem__(self, key, value):48super().__setitem__(key, (value, time.monotonic()))4950def __contains__(self, key):51self._verify_cache()52return {a: b[0] for a, b in self.items()}.__contains__(key)535455def user_cache(timer=300):56cache = TimedCache(timer)5758def wraps(func):59@functools.wraps(func)60async def _wraps(cls, names: list = None, ids: list = None, force=False, token=None):61if not force:62existing = []63if names:64existing.extend([cache[x] for x in names if x in cache])6566if ids:67existing.extend([cache[x] for x in ids if x in cache])6869if len(existing) == (len(names) if names else 0) + (len(ids) if ids else 0):70return existing7172values = await func(cls, names=names, ids=ids, token=token)73for v in values:74cache[v.id] = v75cache[v.name] = v7677return values7879return _wraps8081return wraps828384def id_cache(timer=300):85cache = TimedCache(timer)8687def wraps(func):88@functools.wraps(func)89def _wraps(cls, id: Hashable):90if id in cache:91return cache[id]9293value = func(cls, id)94if value is not None:95cache[id] = value9697return value9899return _wraps100101return wraps102103104