38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
|
|
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()
|