修复招聘公告导出500并增加图片缓存压缩
This commit is contained in:
+1
-1
@@ -771,7 +771,7 @@ app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
|
|||||||
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
|
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
|
||||||
center_duty.install(app, get_db, current_user)
|
center_duty.install(app, get_db, current_user)
|
||||||
center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
|
center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
|
||||||
recruit.install(app, get_db, current_user)
|
recruit.install(app, get_db, current_user, _db_path.parent / 'recruit-images')
|
||||||
|
|
||||||
def timetable_collectors():
|
def timetable_collectors():
|
||||||
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
|
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
|
||||||
|
|||||||
+56
-19
@@ -2,10 +2,13 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import hashlib
|
||||||
import io
|
import io
|
||||||
|
import logging
|
||||||
import re
|
import re
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from html.parser import HTMLParser
|
from html.parser import HTMLParser
|
||||||
|
from pathlib import Path
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin
|
||||||
|
|
||||||
@@ -23,6 +26,8 @@ from .models import recruit_announcements
|
|||||||
SOURCE = "https://school.gxjy.sdei.edu.cn"
|
SOURCE = "https://school.gxjy.sdei.edu.cn"
|
||||||
LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList"
|
LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList"
|
||||||
DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail"
|
DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail"
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
MAX_IMAGE_EDGE = 1800
|
||||||
|
|
||||||
|
|
||||||
class HTMLTextParser(HTMLParser):
|
class HTMLTextParser(HTMLParser):
|
||||||
@@ -129,11 +134,19 @@ def is_image_data(body: bytes) -> bool:
|
|||||||
def normalized_image(body: bytes) -> bytes | None:
|
def normalized_image(body: bytes) -> bytes | None:
|
||||||
try:
|
try:
|
||||||
with Image.open(io.BytesIO(body)) as image:
|
with Image.open(io.BytesIO(body)) as image:
|
||||||
if image.format in {"JPEG", "PNG", "GIF", "BMP", "TIFF"}:
|
|
||||||
return body
|
|
||||||
image.seek(0)
|
image.seek(0)
|
||||||
|
image.load()
|
||||||
|
if max(image.size) > MAX_IMAGE_EDGE:
|
||||||
|
image.thumbnail((MAX_IMAGE_EDGE, MAX_IMAGE_EDGE), Image.Resampling.LANCZOS)
|
||||||
|
if image.mode in {"RGBA", "LA", "P"}:
|
||||||
|
background = Image.new("RGB", image.size, "white")
|
||||||
|
rgba = image.convert("RGBA")
|
||||||
|
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||||
|
image = background
|
||||||
|
else:
|
||||||
|
image = image.convert("RGB")
|
||||||
output = io.BytesIO()
|
output = io.BytesIO()
|
||||||
image.convert("RGB").save(output, format="PNG")
|
image.save(output, format="JPEG", quality=86, optimize=True)
|
||||||
return output.getvalue()
|
return output.getvalue()
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
@@ -144,14 +157,7 @@ def add_docx_picture(document, body: bytes) -> bool:
|
|||||||
document.add_picture(io.BytesIO(body), width=Cm(15))
|
document.add_picture(io.BytesIO(body), width=Cm(15))
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
return False
|
||||||
with Image.open(io.BytesIO(body)) as image:
|
|
||||||
fallback = io.BytesIO()
|
|
||||||
image.convert("RGB").save(fallback, format="PNG")
|
|
||||||
document.add_picture(io.BytesIO(fallback.getvalue()), width=Cm(15))
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None:
|
async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None:
|
||||||
@@ -162,20 +168,43 @@ async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None:
|
|||||||
]
|
]
|
||||||
for attempt, request_headers in enumerate(headers, 1):
|
for attempt, request_headers in enumerate(headers, 1):
|
||||||
try:
|
try:
|
||||||
response = await client.get(url, headers=request_headers)
|
response = await asyncio.wait_for(client.get(url, headers=request_headers), timeout=12)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
body = response.content
|
body = response.content
|
||||||
if is_image_data(body):
|
if is_image_data(body):
|
||||||
normalized = normalized_image(body)
|
normalized = normalized_image(body)
|
||||||
if normalized:
|
if normalized:
|
||||||
return normalized
|
return normalized
|
||||||
except httpx.HTTPError:
|
except (httpx.HTTPError, asyncio.TimeoutError):
|
||||||
pass
|
pass
|
||||||
if attempt < len(headers):
|
if attempt < len(headers):
|
||||||
await asyncio.sleep(0.4 * attempt)
|
await asyncio.sleep(0.4 * attempt)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def cache_file(cache_dir: Path | None, url: str) -> Path | None:
|
||||||
|
if cache_dir is None:
|
||||||
|
return None
|
||||||
|
return cache_dir / (hashlib.sha256(url.encode("utf-8")).hexdigest() + ".jpg")
|
||||||
|
|
||||||
|
|
||||||
|
async def get_image(client: httpx.AsyncClient, url: str, cache_dir: Path | None) -> bytes | None:
|
||||||
|
path = cache_file(cache_dir, url)
|
||||||
|
if path and path.exists():
|
||||||
|
try:
|
||||||
|
return path.read_bytes()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
body = await fetch_image(client, url)
|
||||||
|
if body and path:
|
||||||
|
try:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(body)
|
||||||
|
except OSError:
|
||||||
|
logger.warning("招聘公告图片缓存写入失败:%s", path)
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
def public_row(row) -> dict:
|
def public_row(row) -> dict:
|
||||||
data = dict(row)
|
data = dict(row)
|
||||||
data["detail_url"] = data["wailian"] if data["iswailian"] and data["wailian"] else f"{DETAIL_ENDPOINT}/{data['gonggao_id']}"
|
data["detail_url"] = data["wailian"] if data["iswailian"] and data["wailian"] else f"{DETAIL_ENDPOINT}/{data['gonggao_id']}"
|
||||||
@@ -237,7 +266,7 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
|
|||||||
return {"fetched": len(rows), "added": added, "updated": updated}
|
return {"fetched": len(rows), "added": added, "updated": updated}
|
||||||
|
|
||||||
|
|
||||||
async def docx_bytes(rows, client: httpx.AsyncClient | None = None) -> bytes:
|
async def docx_bytes(rows, client: httpx.AsyncClient | None = None, cache_dir: Path | None = None) -> bytes:
|
||||||
owns_client = client is None
|
owns_client = client is None
|
||||||
if owns_client:
|
if owns_client:
|
||||||
client = httpx.AsyncClient(timeout=20, follow_redirects=True)
|
client = httpx.AsyncClient(timeout=20, follow_redirects=True)
|
||||||
@@ -251,7 +280,7 @@ async def docx_bytes(rows, client: httpx.AsyncClient | None = None) -> bytes:
|
|||||||
|
|
||||||
async def limited(url):
|
async def limited(url):
|
||||||
async with semaphore:
|
async with semaphore:
|
||||||
return await fetch_image(client, url)
|
return await get_image(client, url, cache_dir)
|
||||||
|
|
||||||
results = await asyncio.gather(*(limited(url) for url in sources))
|
results = await asyncio.gather(*(limited(url) for url in sources))
|
||||||
finally:
|
finally:
|
||||||
@@ -302,11 +331,14 @@ def markdown_bytes(rows) -> bytes:
|
|||||||
return ("\n\n---\n\n".join(sections) + "\n").encode("utf-8")
|
return ("\n\n---\n\n".join(sections) + "\n").encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
def install(app, get_db, current_user):
|
def install(app, get_db, current_user, cache_dir: Path | None = None):
|
||||||
@app.post("/api/recruit/sync")
|
@app.post("/api/recruit/sync")
|
||||||
async def sync(viewer=Depends(current_user)):
|
async def sync(viewer=Depends(current_user), db=Depends(get_db)):
|
||||||
async for db in get_db():
|
try:
|
||||||
return await sync_all(db)
|
return await sync_all(db)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("招聘公告同步失败")
|
||||||
|
raise HTTPException(502, "同步失败:暂时无法连接就业平台,请稍后重试") from exc
|
||||||
|
|
||||||
@app.get("/api/recruit/announcements")
|
@app.get("/api/recruit/announcements")
|
||||||
async def announcements(q: str = Query("", max_length=100), db=Depends(get_db), viewer=Depends(current_user)):
|
async def announcements(q: str = Query("", max_length=100), db=Depends(get_db), viewer=Depends(current_user)):
|
||||||
@@ -355,7 +387,12 @@ def install(app, get_db, current_user):
|
|||||||
raise HTTPException(404, "没有匹配的公告")
|
raise HTTPException(404, "没有匹配的公告")
|
||||||
stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S")
|
stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S")
|
||||||
if format == "docx":
|
if format == "docx":
|
||||||
body, extension, media_type = await docx_bytes(rows), "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
try:
|
||||||
|
body = await docx_bytes(rows, cache_dir=cache_dir)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("招聘公告 Word 导出失败")
|
||||||
|
raise HTTPException(502, "Word 导出失败,请稍后重试;Markdown 导出仍可正常使用") from exc
|
||||||
|
extension, media_type = "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||||
else:
|
else:
|
||||||
body, extension, media_type = markdown_bytes(rows), "md", "text/markdown; charset=utf-8"
|
body, extension, media_type = markdown_bytes(rows), "md", "text/markdown; charset=utf-8"
|
||||||
scope = "recruit" if len(rows) > 1 else f"recruit-{rows[0]['gonggao_id']}"
|
scope = "recruit" if len(rows) > 1 else f"recruit-{rows[0]['gonggao_id']}"
|
||||||
|
|||||||
Reference in New Issue
Block a user