first code

This commit is contained in:
Coldin04 2025-08-13 18:49:19 +08:00
commit b18805aa26
11 changed files with 612 additions and 0 deletions

38
services/base_service.py Normal file
View file

@ -0,0 +1,38 @@
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
from datetime import datetime, timedelta
class BaseService(ABC):
"""基础服务类,为扩展提供统一接口"""
def __init__(self):
self.cache = {}
self.cache_timeout = timedelta(seconds=30)
@abstractmethod
def get_data(self, **kwargs) -> Optional[Dict[str, Any]]:
"""获取数据的抽象方法"""
pass
def get_cached_data(self, cache_key: str, **kwargs) -> Optional[Dict[str, Any]]:
"""带缓存的数据获取"""
# 检查缓存
if cache_key in self.cache:
cached_item = self.cache[cache_key]
if datetime.now() - cached_item['timestamp'] < self.cache_timeout:
return cached_item['data']
# 获取新数据
data = self.get_data(**kwargs)
if data:
# 更新缓存
self.cache[cache_key] = {
'data': data,
'timestamp': datetime.now()
}
return data
def clear_cache(self):
"""清理缓存"""
self.cache.clear()