Auto backup \2026-\04-\20
This commit is contained in:
@@ -198,6 +198,74 @@ def update_article_content(
|
||||
return affected > 0
|
||||
|
||||
|
||||
def _cleanup_cover_file(cover_image: str):
|
||||
"""
|
||||
删除封面图文件及对应缩略图(与后台 file_utils.cleanup_file_by_path 逻辑对齐)。
|
||||
|
||||
Args:
|
||||
cover_image: 封面图路径(/storage/admin/images/... 或相对路径)
|
||||
"""
|
||||
if not cover_image or cover_image.startswith(("http://", "https://")):
|
||||
return
|
||||
|
||||
upload_dir = os.path.join(PROJECT_ROOT, "storage", "admin", "images")
|
||||
thumbnail_dir = os.path.join(upload_dir, "thumbnails")
|
||||
|
||||
# 兼容两种路径格式
|
||||
if cover_image.startswith("/storage/admin/images/"):
|
||||
rel_path = cover_image[len("/storage/admin/images/"):]
|
||||
else:
|
||||
rel_path = cover_image.lstrip("/")
|
||||
|
||||
full_path = os.path.join(upload_dir, rel_path)
|
||||
|
||||
# 删除原文件
|
||||
try:
|
||||
if os.path.isfile(full_path):
|
||||
os.remove(full_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# 同步删除缩略图(与原图同名,扩展名 .jpg)
|
||||
try:
|
||||
stem = os.path.splitext(os.path.basename(rel_path))[0]
|
||||
thumb_path = os.path.join(thumbnail_dir, f"{stem}.jpg")
|
||||
if os.path.isfile(thumb_path):
|
||||
os.remove(thumb_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def delete_article(article_id: int) -> bool:
|
||||
"""
|
||||
删除文章(物理删除),同步清理封面图片文件及缩略图。
|
||||
与后台 routers/articles.py 的 delete_article 行为对齐。
|
||||
|
||||
Args:
|
||||
article_id: 文章 ID
|
||||
|
||||
Returns:
|
||||
是否删除成功
|
||||
"""
|
||||
conn = _get_conn()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 先查 cover_image 以便删除后清理文件
|
||||
cursor.execute("SELECT cover_image FROM articles WHERE id = ?", (article_id,))
|
||||
row = cursor.fetchone()
|
||||
cover_image = row["cover_image"] if row else None
|
||||
|
||||
cursor.execute("DELETE FROM articles WHERE id = ?", (article_id,))
|
||||
conn.commit()
|
||||
affected = cursor.rowcount
|
||||
conn.close()
|
||||
|
||||
if affected > 0 and cover_image:
|
||||
_cleanup_cover_file(cover_image)
|
||||
|
||||
return affected > 0
|
||||
|
||||
|
||||
def count_drafts() -> int:
|
||||
"""统计草稿文章数量"""
|
||||
conn = _get_conn()
|
||||
|
||||
Reference in New Issue
Block a user