内容哈希文件缓存模式
使用 SHA-256 内容哈希作为缓存键,缓存昂贵的文件处理结果(PDF 解析、文本提取、图像分析)。与基于路径的缓存不同,此方法在文件移动/重命名后仍然有效,并在内容更改时自动失效。
何时激活
- 构建文件处理管道时(PDF、图像、文本提取)
- 处理成本高且同一文件被重复处理时
- 需要一个
--cache/--no-cacheCLI 选项时 - 希望在不修改现有纯函数的情况下为其添加缓存时
核心模式
1. 基于内容哈希的缓存键
使用文件内容(而非路径)作为缓存键:
import hashlib
from pathlib import Path
_HASH_CHUNK_SIZE = 65536 # 64KB chunks for large files
def compute_file_hash(path: Path) -> str:
"""SHA-256 of file contents (chunked for large files)."""
if not path.is_file():
raise FileNotFoundError(f"File not found: {path}")
sha256 = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(_HASH_CHUNK_SIZE)
if not chunk:
break
sha256.update(chunk)
return sha256.hexdigest()
为什么使用内容哈希? 文件重命名/移动 = 缓存命中。内容更改 = 自动失效。无需索引文件。
2. 用于缓存条目的冻结数据类
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class CacheEntry:
file_hash: str
source_path: str
document: ExtractedDocument # The cached result
3. 基于文件的缓存存储
每个缓存条目都存储为 {hash}.json —— 通过哈希实现 O(1) 查找,无需索引文件。
import json
from typing import Any
de…