51 lines
2.1 KiB
Python
51 lines
2.1 KiB
Python
"""缩略图接口:列表页取图的唯一入口(实现在 services/thumbs.py)。
|
||
|
||
GET /api/media/thumb/{width}/{媒体库相对路径}
|
||
|
||
宽高只需给一个宽度:等比缩放、只缩不放,档位向上取整到固定几档,
|
||
这样同一个源文件在全站(资产库卡片 / 分镜关键帧 / 审片缩略 / 时间线)
|
||
最多只有几个缓存变体,而不是每个 CSS 尺寸一份。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from email.utils import formatdate
|
||
from urllib.parse import quote
|
||
|
||
from fastapi import APIRouter, HTTPException
|
||
from fastapi.responses import FileResponse, RedirectResponse
|
||
|
||
from app.services import thumbs
|
||
|
||
router = APIRouter(tags=["media"])
|
||
|
||
|
||
@router.get("/api/media/thumb/{width}/{full_path:path}")
|
||
def thumbnail(width: int, full_path: str):
|
||
"""按需生成并返回缩略图;不值得缩略或生成失败时回到原图,文件不存在才报 404。"""
|
||
target = thumbs.resolve(full_path)
|
||
if target is None:
|
||
raise HTTPException(status_code=404, detail="媒体文件不存在")
|
||
original = thumbs.original_url(target)
|
||
made = thumbs.build(target, width)
|
||
if made is None:
|
||
return RedirectResponse(original, status_code=307)
|
||
stat = made.stat()
|
||
return FileResponse(
|
||
made,
|
||
media_type=thumbs.MEDIA_TYPES.get(made.suffix, "application/octet-stream"),
|
||
headers={
|
||
# URL 里带了源文件 mtime+size 派生的缓存键语义(键变了就换文件),
|
||
# 因此可以放心让浏览器长期缓存,翻页/切页签都不必重新下载。
|
||
"Cache-Control": "public, max-age=604800, immutable",
|
||
"ETag": f'"{made.stem}"',
|
||
"Last-Modified": _http_date(stat.st_mtime),
|
||
# 排查用:这张缩略图来自哪张原图(HTTP 头只能是 latin-1,中文路径必须先转义)
|
||
"X-Thumb-Source": quote(original, safe="/:=%"),
|
||
},
|
||
)
|
||
|
||
|
||
def _http_date(epoch: float) -> str:
|
||
"""HTTP 日期头(FileResponse 不像 StaticFiles 会自己带 Last-Modified)。"""
|
||
return formatdate(timeval=epoch, usegmt=True)
|