Python/短视频合成自动化/caches.py

116 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""
缓存模块
"""
# 列举导入模块
import json
from pathlib import Path
from pathlib import WindowsPath
import sys
import time
from typing import Any, Dict, Optional
sys.path.append(Path(__file__).parent.parent.as_posix())
from utils.sqlite import SQLite
class Caches(SQLite):
"""
缓存客户端,支持:
query查询并返回单条缓存
update新增或更新单条缓存
"""
# 自定义JSON编码器
class JSONEncoder(json.JSONEncoder):
def default(self, o):
# 若为WindowsPath对象则转为字符串路径
if isinstance(o, WindowsPath):
return o.as_posix()
return super().default(o)
def __init__(self, cache_ttl: int = 30 * 86400):
"""
初始化
:param cache_ttl: 缓存生存时间单位为秒默认为30天
"""
# 初始化
super().__init__(database=Path(__file__).parent.resolve() / "caches.db")
self.cache_ttl = cache_ttl
# 初始化缓存表(不清理过期缓存)
try:
with self:
self.execute(
sql="""
CREATE TABLE IF NOT EXISTS caches
(
--草稿名称
draft_name TEXT PRIMARY KEY,
--工作流配置
configurations TEXT NOT NULL,
--创建时间戳
timestamp REAL NOT NULL
)
"""
)
self.execute(
sql="""
CREATE INDEX IF NOT EXISTS idx_timestamp ON caches(timestamp)
"""
)
except Exception as exception:
raise RuntimeError(f"初始化缓存发生异常:{str(exception)}") from exception
def query(self, draft_name: str) -> Optional[Dict[str, Any]]:
"""
查询并返回单条缓存
:param draft_name: 草稿名称
:return: 缓存
"""
try:
with self:
result = self.query_one(
sql="""
SELECT configurations
FROM caches
WHERE draft_name = ? AND timestamp >= ?
""",
parameters=(draft_name, time.time() - self.cache_ttl),
)
return None if result is None else json.loads(result["configurations"])
except Exception as exception:
raise RuntimeError(
f"查询并获取单条缓存发生异常:{str(exception)}"
) from exception
def update(
self, draft_name: str, configurations: Dict[str, Dict[str, Any]]
) -> Optional[bool]:
"""
新增或更新单条缓存
:param draft_name: 草稿名称
:param configurations: 节点配置
:return: 成功返回True失败返回False
"""
try:
with self:
return self.execute(
sql="""
INSERT OR REPLACE INTO caches (draft_name, configurations, timestamp) VALUES (?, ?, ?)
""",
parameters=(
draft_name,
json.dumps(
obj=configurations,
cls=self.JSONEncoder,
sort_keys=True,
ensure_ascii=False,
),
time.time(),
),
)
except Exception as exception:
raise RuntimeError("新增或更新缓存发生异常") from exception