forked from iti-framework/iTi-Flask
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.7 KiB
Python
71 lines
1.7 KiB
Python
from abc import ABC, abstractmethod
|
|
from iti.applications.common import setup_logger
|
|
from flask import current_app
|
|
|
|
logger = setup_logger(__name__)
|
|
|
|
|
|
class BaseEventHandler(ABC):
|
|
"""
|
|
事件处理器基类
|
|
"""
|
|
|
|
def __init__(self, order: int = 0, async_mode: bool = False):
|
|
self.order = order
|
|
self.async_mode = async_mode
|
|
|
|
@abstractmethod
|
|
def handle(self, data: any) -> any:
|
|
"""
|
|
处理事件
|
|
"""
|
|
pass
|
|
|
|
def before_handle(self, data: any) -> any:
|
|
"""
|
|
处理事件前
|
|
"""
|
|
return data
|
|
|
|
def after_handle(self, data: any) -> any:
|
|
"""
|
|
处理事件后
|
|
"""
|
|
return data
|
|
|
|
def on_error(self, error: Exception, data: any) -> None:
|
|
"""
|
|
处理事件错误
|
|
"""
|
|
logger.error(f"事件处理错误: {error}, 数据: {data}", exc_info=True)
|
|
|
|
|
|
class FlaskEventHandler(BaseEventHandler):
|
|
"""Flask 事件处理器基类"""
|
|
|
|
def __init__(self, order: int = 0, async_mode: bool = False):
|
|
super().__init__(order, async_mode)
|
|
self._app = None
|
|
|
|
@property
|
|
def app(self):
|
|
"""获取 Flask 应用实例"""
|
|
if self._app is None:
|
|
self._app = current_app
|
|
return self._app
|
|
|
|
def handle(self, data: any) -> any:
|
|
"""处理事件"""
|
|
try:
|
|
data = self.before_handle(data)
|
|
result = self._do_handle(data)
|
|
result = self.after_handle(result)
|
|
return result
|
|
except Exception as e:
|
|
self.on_error(e, data)
|
|
raise
|
|
|
|
def _do_handle(self, data: any) -> any:
|
|
"""实际处理逻辑"""
|
|
pass
|