Core Modules¶
The core modules provide the foundational architecture for EmailWidget, including the Widget base class, template engine, cache system, and other core components.
BaseWidget¶
BaseWidget(widget_id=None)
¶
Bases: ABC
Abstract base class for all widgets.
This class defines the basic interface and common functionality that all widgets must implement. Each widget has a unique ID and can be added to an Email container.
Attributes:
Name | Type | Description |
---|---|---|
widget_id |
str
|
Unique identifier for the widget. |
parent |
Optional[Email]
|
Email container that contains this widget. |
Examples:
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"}
# Instantiate custom widget
widget = MyCustomWidget()
print(widget.widget_id) # Print generated unique ID
html_output = widget.render_html()
print(html_output) # Print rendered HTML
Initialize BaseWidget.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
widget_id
|
Optional[str]
|
Optional widget ID, automatically generated if not provided. |
None
|
Attributes¶
parent
property
¶
Get the Email container that contains this widget.
Returns:
Type | Description |
---|---|
Optional[Email]
|
Optional[Email]: Email object containing this widget, or None if not added to a container. |
widget_id
property
¶
Get the unique ID of the widget.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Unique identifier string for the widget. |
Functions¶
get_template_context()
abstractmethod
¶
Get the context data required for template rendering.
Subclasses must implement this method to return the data dictionary needed for template rendering.
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dict[str, Any]: Template context data dictionary. |
render_html()
¶
Render the widget as an HTML string.
Uses the template engine to render the widget with comprehensive error handling. Returns error HTML if rendering fails.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Rendered HTML string. |
Examples:
set_widget_id(widget_id)
¶
Set the widget ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
widget_id
|
str
|
New widget ID. |
required |
Returns:
Name | Type | Description |
---|---|---|
BaseWidget |
BaseWidget
|
Returns self to support method chaining. |
Examples:
TemplateEngine¶
TemplateEngine()
¶
Template rendering engine.
Provides unified template rendering interface with template caching and error handling.
Core Features
- Template Rendering: Uses Jinja2 to render Widget templates.
- Cache Management: Template compilation caching improves performance.
- Error Handling: Safe template rendering and error recovery.
- Context Processing: Automatic handling of template context data.
Examples:
from email_widget.core.template_engine import get_template_engine
engine = get_template_engine()
# Render a simple template
html = engine.render_safe(
"<div>Hello, {{ name }}!</div>",
{"name": "EmailWidget"}
)
print(html) # Output: <div>Hello, EmailWidget!</div>
# Render a template with errors and use fallback content
error_html = engine.render_safe(
"<div>{% for item in items %} {{ item.name }} {% endfor %}</div>",
{"items": "not_a_list"}, # Intentionally pass wrong type
fallback="<div>Rendering failed, please contact administrator.</div>"
)
print(error_html) # Output: <div>Rendering failed, please contact administrator.</div>
Initialize template engine.
Functions¶
clear_cache()
¶
Clear template cache.
get_cache_stats()
¶
Get cache statistics.
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dict[str, Any]: Cache statistics dictionary, including cached template count and total size (bytes). |
render(template_string, context)
¶
Render template.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
template_string
|
str
|
Template string. |
required |
context
|
Dict[str, Any]
|
Template context data. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Rendered HTML string. |
Raises:
Type | Description |
---|---|
TemplateError
|
Thrown when template rendering fails. |
render_safe(template_string, context, fallback='')
¶
Safely render template.
Returns fallback content instead of throwing exception on rendering failure.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
template_string
|
str
|
Template string. |
required |
context
|
Dict[str, Any]
|
Template context data. |
required |
fallback
|
str
|
Fallback content on rendering failure. |
''
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Rendered HTML string or fallback content. |
validate_template(template_string)
¶
Validate template syntax.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
template_string
|
str
|
Template string. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Whether template syntax is correct. |
ImageCache¶
ImageCache(cache_dir=None, max_size=100)
¶
LRU cache system for improving image processing performance.
This cache manager uses the Least Recently Used (LRU) strategy to manage image data, supports storing images to the filesystem, and maintains an in-memory index for fast lookup. This significantly improves performance when embedding large amounts of images in emails by avoiding redundant downloading and processing.
Core Features
- LRU Strategy: Automatically evicts least recently used cache items.
- Filesystem Storage: Persists image data to local files, reducing memory usage.
- Memory Index: Fast cache item lookup, improving access speed.
- Performance Monitoring: Provides cache hit rate and size statistics.
Attributes:
Name | Type | Description |
---|---|---|
_cache_dir |
Path
|
Directory for storing cache files. |
_max_size |
int
|
Maximum number of items allowed in cache. |
_cache_index |
Dict[str, Dict[str, Any]]
|
In-memory cache index. |
Examples:
from email_widget.core.cache import get_image_cache
cache = get_image_cache()
# Store data
# Assuming some_image_data is the binary content of an image, mime_type is the MIME type
# cache.set("image_url_or_path_1", some_image_data, "image/png")
# Get data
# cached_data = cache.get("image_url_or_path_1")
# if cached_data:
# image_bytes, mime = cached_data
# print(f"Retrieved image from cache, size: {len(image_bytes)} bytes, type: {mime}")
# Clear cache
# cache.clear()
# Get cache statistics
stats = cache.get_cache_stats()
print(f"Cache items: {stats['total_items']}, total size: {stats['total_size_bytes']} bytes")
Initialize the cache manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cache_dir
|
Optional[Path]
|
Cache directory path, defaults to |
None
|
max_size
|
int
|
Maximum number of items allowed in cache, defaults to 100. |
100
|
Functions¶
clear()
¶
Clear all cache data.
This method will delete all cache files and cache index.
get(source)
¶
Get image data from cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str
|
Image source (URL or file path), used to generate cache key. |
required |
Returns:
Type | Description |
---|---|
tuple[bytes, str] | None
|
Optional[Tuple[bytes, str]]: If cache found, returns (image binary data, MIME type) tuple; otherwise returns None. |
get_cache_stats()
¶
Get cache statistics
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Cache statistics dictionary |
set(source, data, mime_type='image/png')
¶
Store image data in cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str
|
Image source (URL or file path), used as cache key. |
required |
data
|
bytes
|
Image binary data. |
required |
mime_type
|
str
|
Image MIME type, defaults to "image/png". |
'image/png'
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Whether successfully stored in cache. |
Logger¶
EmailWidgetLogger
¶
EmailWidget project dedicated logger.
Provides unified logging interface with environment variable control for log levels. Can completely disable log output in production environment.
Log Levels
DEBUG
: Debug information, detailed information during development stage.INFO
: General information, normal operation records.WARNING
: Warning information, potential problem alerts.ERROR
: Error information, errors but not fatal problems.CRITICAL
: Critical errors, system-level serious problems.
Environment Variable Configuration
EMAILWIDGET_LOG_LEVEL
: Set log level, e.g.,DEBUG
,INFO
,WARNING
,ERROR
,CRITICAL
.EMAILWIDGET_DISABLE_LOGGING
: Set totrue
,1
,yes
to completely disable log output.
Examples:
from email_widget.core.logger import get_project_logger
logger = get_project_logger()
# Log different levels
logger.debug("Debug info: template rendering started")
logger.info("Email created successfully")
logger.warning("Used deprecated method")
logger.error("Widget rendering failed")
logger.critical("System memory insufficient")
You can also use convenience functions directly:
from email_widget.core.logger import info, error
info("This is an info log.")
error("This is an error log.")
Functions¶
critical(message)
¶
Output critical error log.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Log message. |
required |
debug(message)
¶
Output debug log.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Log message. |
required |
error(message)
¶
Output error log.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Log message. |
required |
info(message)
¶
Output info log.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Log message. |
required |
warning(message)
¶
Output warning log.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Log message. |
required |