跳转至

核心模块

核心模块提供了 EmailWidget 的基础架构,包括 Widget 基类、模板引擎、缓存系统等核心组件。

BaseWidget

BaseWidget(widget_id=None)

Bases: ABC

所有Widget的基础抽象类。

这个类定义了所有Widget必须实现的基本接口和通用功能。 每个Widget都有一个唯一的ID,可以被添加到Email容器中。

Attributes:

Name Type Description
widget_id str

Widget的唯一标识符。

parent Optional[Email]

包含此Widget的Email容器。

Examples:

Python
from abc import ABC, abstractmethod
from email_widget.core.base import BaseWidget
from typing import Dict, Any, Optional

class MyCustomWidget(BaseWidget):
    TEMPLATE = "<div>Hello from Custom Widget!</div>"

    def _get_template_name(self) -> str:
        return "my_custom_widget.html"

    def get_template_context(self) -> Dict[str, Any]:
        return {"message": "This is a custom message.", "data": "some data"}

# 实例化自定义Widget
widget = MyCustomWidget()
print(widget.widget_id) # 打印生成的唯一ID
html_output = widget.render_html()
print(html_output) # 打印渲染后的HTML

初始化BaseWidget。

Parameters:

Name Type Description Default
widget_id Optional[str]

可选的Widget ID,如果不提供则自动生成。

None

Attributes

parent property

获取包含此Widget的Email容器。

Returns:

Type Description
Optional[Email]

Optional[Email]: 包含此Widget的Email对象,如果未被添加到容器中则返回None。

widget_id property

获取Widget的唯一ID。

Returns:

Name Type Description
str str

Widget的唯一标识符字符串。

Functions

get_template_context() abstractmethod

获取模板渲染所需的上下文数据。

子类必须实现此方法,返回模板渲染所需的数据字典。

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: 模板上下文数据字典。

render_html()

将Widget渲染为HTML字符串。

使用模板引擎渲染Widget,包含完整的容错机制。如果渲染失败,会返回错误提示的HTML。

Returns:

Name Type Description
str str

渲染后的HTML字符串。

Examples:

Python
class MyWidget(BaseWidget):
    TEMPLATE = "<div>{{ content }}</div>"

    def _get_template_name(self):
        return "my_widget.html"

    def get_template_context(self):
        return {"content": "Hello World"}

widget = MyWidget()
html = widget.render_html()
print(html)  # <div>Hello World</div>
set_widget_id(widget_id)

设置Widget的ID。

Parameters:

Name Type Description Default
widget_id str

新的Widget ID。

required

Returns:

Name Type Description
BaseWidget BaseWidget

返回self以支持链式调用。

Examples:

Python Console Session
>>> widget.set_widget_id("my_custom_id")
>>> print(widget.widget_id)  # 输出: my_custom_id

TemplateEngine

TemplateEngine()

模板渲染引擎.

提供统一的模板渲染接口,支持模板缓存和错误处理.

核心功能
  • 模板渲染: 使用 Jinja2 渲染 Widget 模板.
  • 缓存管理: 模板编译缓存提升性能.
  • 错误处理: 安全的模板渲染和错误恢复.
  • 上下文处理: 自动处理模板上下文数据.

Examples:

Python
from email_widget.core.template_engine import get_template_engine

engine = get_template_engine()

# 渲染一个简单的模板
html = engine.render_safe(
    "<div>Hello, {{ name }}!</div>",
    {"name": "EmailWidget"}
)
print(html) # 输出: <div>Hello, EmailWidget!</div>

# 渲染一个带有错误的模板,并使用降级内容
error_html = engine.render_safe(
    "<div>{% for item in items %} {{ item.name }} {% endfor %}</div>",
    {"items": "not_a_list"}, # 故意传入错误类型
    fallback="<div>渲染失败,请联系管理员.</div>"
)
print(error_html) # 输出: <div>渲染失败,请联系管理员.</div>

初始化模板引擎.

Functions

clear_cache()

清空模板缓存.

get_cache_stats()

获取缓存统计信息.

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: 缓存统计信息字典,包含缓存的模板数量和总大小(字节).

render(template_string, context)

渲染模板.

Parameters:

Name Type Description Default
template_string str

模板字符串.

required
context Dict[str, Any]

模板上下文数据.

required

Returns:

Name Type Description
str str

渲染后的HTML字符串.

Raises:

Type Description
TemplateError

模板渲染失败时抛出.

render_safe(template_string, context, fallback='')

安全渲染模板.

在渲染失败时返回降级内容而不是抛出异常.

Parameters:

Name Type Description Default
template_string str

模板字符串.

required
context Dict[str, Any]

模板上下文数据.

required
fallback str

渲染失败时的降级内容.

''

Returns:

Name Type Description
str str

渲染后的HTML字符串或降级内容.

validate_template(template_string)

验证模板语法.

Parameters:

Name Type Description Default
template_string str

模板字符串.

required

Returns:

Name Type Description
bool bool

模板语法是否正确.

ImageCache

ImageCache(cache_dir=None, max_size=100)

LRU 缓存系统,用于提升图片处理性能.

该缓存管理器使用最近最少使用(LRU)策略来管理图片数据, 支持将图片存储到文件系统,并维护内存中的索引以实现快速查找. 这对于在邮件中嵌入大量图片时,避免重复下载和处理,从而显著提升性能.

核心功能
  • LRU 策略: 自动淘汰最久未使用的缓存项.
  • 文件系统存储: 将图片数据持久化到本地文件,减少内存占用.
  • 内存索引: 快速查找缓存项,提高访问速度.
  • 性能监控: 提供缓存命中率和大小统计.

Attributes:

Name Type Description
_cache_dir Path

缓存文件存储的目录.

_max_size int

缓存中允许的最大项目数量.

_cache_index Dict[str, Dict[str, Any]

内存中的缓存索引.

Examples:

Python
from email_widget.core.cache import get_image_cache

cache = get_image_cache()

# 存储数据
# 假设 some_image_data 是图片的二进制内容,mime_type 是图片的MIME类型
# cache.set("image_url_or_path_1", some_image_data, "image/png")

# 获取数据
# cached_data = cache.get("image_url_or_path_1")
# if cached_data:
#     image_bytes, mime = cached_data
#     print(f"从缓存获取图片,大小: {len(image_bytes)} 字节, 类型: {mime}")

# 清空缓存
# cache.clear()

# 获取缓存统计信息
stats = cache.get_cache_stats()
print(f"缓存项目数量: {stats['total_items']}, 总大小: {stats['total_size_bytes']} 字节")

初始化缓存管理器.

Parameters:

Name Type Description Default
cache_dir Optional[Path]

缓存目录路径,默认为系统临时目录下的 emailwidget_cache.

None
max_size int

缓存中允许的最大项目数量,默认为100.

100

Functions

clear()

清空所有缓存数据.

此方法会删除所有缓存文件和缓存索引.

get(source)

从缓存中获取图片数据.

Parameters:

Name Type Description Default
source str

图片源(URL或文件路径),用于生成缓存键.

required

Returns:

Type Description
tuple[bytes, str] | None

Optional[Tuple[bytes, str]]: 如果找到缓存,返回 (图片二进制数据, MIME类型) 的元组; 否则返回None.

get_cache_stats()

获取缓存统计信息

Returns:

Type Description
dict[str, Any]

缓存统计信息字典

set(source, data, mime_type='image/png')

向缓存中存储图片数据.

Parameters:

Name Type Description Default
source str

图片源(URL或文件路径),作为缓存的键.

required
data bytes

图片的二进制数据.

required
mime_type str

图片的MIME类型,默认为 "image/png".

'image/png'

Returns:

Name Type Description
bool bool

是否成功存储到缓存.

Logger

EmailWidgetLogger

EmailWidget项目专用日志器.

提供统一的日志接口,支持通过环境变量控制日志级别. 在生产环境中可以完全禁用日志输出.

日志级别
  • DEBUG: 调试信息,开发阶段的详细信息.
  • INFO: 一般信息,正常操作记录.
  • WARNING: 警告信息,可能的问题提醒.
  • ERROR: 错误信息,错误但不致命的问题.
  • CRITICAL: 严重错误,系统级严重问题.
环境变量配置
  • EMAILWIDGET_LOG_LEVEL: 设置日志级别,例如 DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • EMAILWIDGET_DISABLE_LOGGING: 设置为 true, 1, yes 可以完全禁用日志输出.

Examples:

Python
from email_widget.core.logger import get_project_logger

logger = get_project_logger()

# 记录不同级别的日志
logger.debug("调试信息: 模板渲染开始")
logger.info("邮件创建成功")
logger.warning("使用了过时的方法")
logger.error("Widget 渲染失败")
logger.critical("系统内存不足")

也可以直接使用便捷函数:

Python
from email_widget.core.logger import info, error

info("这是一个信息日志.")
error("这是一个错误日志.")

Functions

__new__()

单例模式确保全局唯一的日志器实例.

Returns:

Name Type Description
EmailWidgetLogger EmailWidgetLogger

全局唯一的日志器实例.

critical(message)

输出严重错误日志.

Parameters:

Name Type Description Default
message str

日志消息.

required
debug(message)

输出调试日志.

Parameters:

Name Type Description Default
message str

日志消息.

required
error(message)

输出错误日志.

Parameters:

Name Type Description Default
message str

日志消息.

required
info(message)

输出信息日志.

Parameters:

Name Type Description Default
message str

日志消息.

required
warning(message)

输出警告日志.

Parameters:

Name Type Description Default
message str

日志消息.

required