Skip to content

Commit f5fa352

Browse files
committed
➕ expiringdict替换为expiringdictx
1 parent 3454032 commit f5fa352

File tree

6 files changed

+117
-78
lines changed

6 files changed

+117
-78
lines changed

nonebot_bison/admin_page/token_manager.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import random
22
import string
3+
from datetime import timedelta
34

4-
from expiringdict import ExpiringDict
5+
from expiringdictx import ExpiringDict
56

67

78
class TokenManager:
89
def __init__(self):
9-
self.token_manager = ExpiringDict(max_len=100, max_age_seconds=60 * 10)
10+
self.token_manager = ExpiringDict[str, tuple](capacity=100, default_age=timedelta(minutes=10))
1011

1112
def get_user(self, token: str) -> tuple | None:
1213
res = self.token_manager.get(token)

nonebot_bison/platform/ceobecanteen/cache.py

+6-42
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from functools import partial
2+
from datetime import timedelta
23
from types import MappingProxyType
34
from collections.abc import Callable
4-
from typing import Any, TypeVar, cast
5-
from datetime import datetime, timedelta
65

7-
from expiringdict import ExpiringDict
6+
from expiringdictx import ExpiringDict
87
from hishel import Controller, AsyncCacheClient, AsyncFileStorage
98

109
from .const import DATASOURCE_URL
@@ -18,47 +17,12 @@
1817
storage=AsyncFileStorage(ttl=300),
1918
)
2019

21-
StoreType = TypeVar("StoreType")
22-
23-
24-
class SimpleCache:
25-
"""简单缓存"""
26-
27-
def __init__(self, default_lifetime: timedelta = timedelta(minutes=5)):
28-
self.default_lifetime = default_lifetime
29-
self._cache: dict[str, tuple[Any, datetime, timedelta]] = {}
30-
31-
def __setitem__(self, key: str, value: tuple[Any, timedelta | None]):
32-
value, lifetime = value
33-
self._cache[key] = (value, datetime.now(), lifetime or self.default_lifetime)
34-
35-
def __getitem__(self, key: str):
36-
if item := self._cache.get(key):
37-
value, create_time, lifetime = item
38-
if datetime.now() - create_time <= lifetime:
39-
return value
40-
else:
41-
del self._cache[key]
42-
return None
43-
44-
def set(self, key: str, value: Any, lifetime: timedelta | None = None):
45-
self[key] = (value, lifetime)
46-
47-
def get(
48-
self, key: str, default: Any = None, value_convert_func: Callable[[Any], StoreType | None] | None = None
49-
) -> StoreType | None:
50-
if value := self[key]:
51-
if value_convert_func:
52-
return value_convert_func(value)
53-
return value
54-
return default
55-
5620

5721
class CeobeDataSourceCache:
5822
"""数据源缓存"""
5923

6024
def __init__(self):
61-
self._cache = ExpiringDict(max_len=100, max_age_seconds=60 * 60 * 24 * 7)
25+
self._cache = ExpiringDict[str, CeobeTarget](capacity=100, default_age=timedelta(days=7))
6226
self.client = CeobeClient()
6327
self.url = DATASOURCE_URL
6428
self.init_requested = False
@@ -86,7 +50,7 @@ def select_one(self, cond_func: Callable[[CeobeTarget], bool]) -> CeobeTarget |
8650
8751
不会刷新缓存
8852
"""
89-
cache = cast(list[CeobeTarget], self._cache.values())
53+
cache = self._cache.values()
9054
return next(filter(cond_func, cache), None)
9155

9256
async def get_by_unique_id(self, unique_id: str) -> CeobeTarget | None:
@@ -95,9 +59,9 @@ async def get_by_unique_id(self, unique_id: str) -> CeobeTarget | None:
9559
如果在缓存中找不到,会刷新缓存
9660
"""
9761
if target := self._cache.get(unique_id):
98-
return cast(CeobeTarget, target)
62+
return target
9963
await self.refresh_data_sources()
100-
return cast(CeobeTarget | None, self._cache.get(unique_id))
64+
return self._cache.get(unique_id)
10165

10266
async def get_by_nickname(self, nickname: str) -> CeobeTarget | None:
10367
"""根据nickname获取数据源

nonebot_bison/platform/ceobecanteen/platform.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@
33

44
from nonebot import logger
55
from hishel import AsyncCacheClient
6+
from expiringdictx import SimpleCache
67

78
from ...post import Post
89
from ..platform import NewMessage
910
from .utils import process_response
1011
from ...utils import SchedulerConfig
1112
from ...types import Target, RawPost, Category
13+
from .cache import CeobeClient, CeobeDataSourceCache
1214
from .const import COMB_ID_URL, COOKIES_URL, COOKIE_ID_URL
13-
from .cache import CeobeClient, SimpleCache, CeobeDataSourceCache
1415
from .models import CeobeCookie, CombIdResponse, CookiesResponse, CookieIdResponse
1516

1617

@@ -57,7 +58,7 @@ async def get_comb_id(self, targets: list[Target] | None = None, force_refresh:
5758
)
5859
comb_id = process_response(resp, CombIdResponse).data["datasource_comb_id"]
5960
logger.trace(f"get comb_id: {comb_id}")
60-
self.cache_store["comb_id"] = (comb_id, timedelta(hours=12))
61+
self.cache_store["comb_id", timedelta(hours=12)] = comb_id
6162

6263
return self.cache_store["comb_id"]
6364

@@ -83,8 +84,8 @@ async def request():
8384

8485
def update(cookie_id: str, cookies: list[CeobeCookie]):
8586
lifetime = timedelta(hours=1)
86-
self.cache_store["cookie_id"] = (cookie_id, lifetime)
87-
self.cache_store["cookies"] = (cookies, lifetime)
87+
self.cache_store["cookie_id", lifetime] = cookie_id
88+
self.cache_store["cookies", lifetime] = cookies
8889

8990
if cookie_id != self.cache_store["cookie_id"] or force_refresh:
9091
logger.trace(f"cookie_id changed: {self.cache_store['cookie_id']} -> {cookie_id}, request cookies")

0 commit comments

Comments
 (0)