fix(cache): support clear image cache

This commit is contained in:
InfinityPacer
2024-10-20 01:05:06 +08:00
parent c6febe4755
commit 2c8ecdfcb9
3 changed files with 17 additions and 8 deletions

View File

@@ -76,7 +76,7 @@ def fetch_image(
try:
content = cache_path.read_bytes()
etag = HashUtils.md5(content)
headers = RequestUtils.generate_cache_headers(etag)
headers = RequestUtils.generate_cache_headers(etag, max_age=86400 * 7)
if if_none_match == etag:
return Response(status_code=304, headers=headers)
return Response(content=content, media_type="image/jpeg", headers=headers)

View File

@@ -64,10 +64,12 @@ def stop_frontend():
def clear_temp():
"""
清理临时目录中3天前的文件
清理临时文件和图片缓存
"""
# 清理3天前的文件
# 清理临时目录中3天前的文件
SystemUtils.clear(settings.TEMP_PATH, days=3)
# 清理图片缓存目录中7天前的文件
SystemUtils.clear(settings.CACHE_PATH / "images", days=7)
def check_auth():

View File

@@ -7,7 +7,7 @@ import subprocess
import sys
from glob import glob
from pathlib import Path
from typing import List, Union, Tuple, Optional
from typing import List, Optional, Tuple, Union
import docker
import psutil
@@ -537,11 +537,18 @@ class SystemUtils:
@staticmethod
def clear(temp_path: Path, days: int):
"""
清理临时目录中指定天数前的文件
清理指定目录中指定天数前的文件,递归删除子文件及空文件夹
"""
if not temp_path.exists():
return
for file in temp_path.glob('*'):
if file.is_file() \
and (datetime.datetime.now() - datetime.datetime.fromtimestamp(file.stat().st_mtime)).days > days:
# 遍历目录及子目录中的所有文件和文件夹
for file in temp_path.rglob('*'):
# 如果是文件并且符合时间条件,则删除
if file.is_file() and (
datetime.datetime.now() - datetime.datetime.fromtimestamp(file.stat().st_mtime)).days > days:
file.unlink()
# 删除空的文件夹
for folder in sorted(temp_path.rglob('*'), reverse=True):
# 确保是空文件夹
if folder.is_dir() and not any(folder.iterdir()):
folder.rmdir()