Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
158 lines (123 loc) · 5.17 KB
/
Copy pathserver.py
File metadata and controls
158 lines (123 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""html2pdf Web 后端 — FastAPI 包装 html2pdf.py 的转换逻辑。
用法:
uv run server.py # 默认 http://127.0.0.1:8000
接口:
POST /api/convert/batch
{"items": [{"url": "...", "filename": "可选"}, ...], "mode": "full|content"}
单个任务直接返回 PDF 文件流;多个任务并行转换后打包 zip 返回。
失败的条目会写入 zip 内的 _失败列表.txt。
浏览器实例全局复用,避免每次转换都重启浏览器。
"""
import asyncio
import re
import shutil
import tempfile
import zipfile
from datetime import datetime
from pathlib import Path
from fastapi import BackgroundTasks, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from playwright.async_api import async_playwright
from pydantic import BaseModel, HttpUrl
from html2pdf import html2pdf_async, sanitize_filename
# 转换输出目录(临时目录,重启自动清理)
OUT_DIR = Path(tempfile.mkdtemp(prefix='html2pdf-'))
# 并行转换上限,避免同时开太多页面把内存打满
MAX_CONCURRENT = 3
app = FastAPI(title='html2pdf')
# 开发环境允许 Vite dev server 跨域
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:5173', 'http://127.0.0.1:5173'],
allow_methods=['*'],
allow_headers=['*'],
)
# 全局共享的浏览器实例(懒加载,断线自动重连)
_pw = None
_browser = None
_browser_lock = asyncio.Lock()
_sem = asyncio.Semaphore(MAX_CONCURRENT)
async def get_browser():
global _pw, _browser
async with _browser_lock:
if _browser is None or not _browser.is_connected():
_pw = await async_playwright().start()
_browser = await _pw.chromium.launch()
return _browser
class ConvertItem(BaseModel):
url: HttpUrl
filename: str | None = None # 自定义文件名(不带扩展名),为空则用页面标题
class BatchRequest(BaseModel):
items: list[ConvertItem]
mode: str = 'full'
def _safe_title(url: str) -> str:
"""URL 兜底文件名(取不到页面标题时使用)。"""
host = re.sub(r'^https?://', '', url).split('/')[0]
return sanitize_filename(host) or 'output'
def _unique_path(directory: Path, name: str) -> Path:
"""目录下不重名的路径,重名时追加 -2、-3…"""
p = directory / name
stem, suffix = p.stem, p.suffix
n = 2
while p.exists():
p = directory / f'{stem}-{n}{suffix}'
n += 1
return p
async def _convert_one(item: ConvertItem, mode: str, workdir: Path):
"""转换单个 URL,返回 (url, 输出路径 | None, 错误信息 | None)。"""
url = str(item.url)
async with _sem:
try:
browser = await get_browser()
output = None
if item.filename and item.filename.strip():
output = str(_unique_path(workdir, sanitize_filename(item.filename) + '.pdf'))
path = Path(await html2pdf_async(browser, url, output, mode))
# 未指定文件名时输出在当前目录,移入工作目录
if path.parent != workdir:
dest = _unique_path(workdir, path.name)
shutil.move(str(path), dest)
path = dest
return (url, path, None)
except Exception as e:
return (url, None, str(e))
@app.post('/api/convert/batch')
async def convert_batch(req: BatchRequest, background: BackgroundTasks):
if req.mode not in ('full', 'content'):
raise HTTPException(status_code=422, detail="mode 必须是 'full' 或 'content'")
if not req.items:
raise HTTPException(status_code=422, detail='items 不能为空')
workdir = Path(tempfile.mkdtemp(prefix='batch-', dir=OUT_DIR))
results = await asyncio.gather(
*[_convert_one(item, req.mode, workdir) for item in req.items]
)
ok = [(u, p) for u, p, e in results if p is not None]
failed = [(u, e) for u, p, e in results if e is not None]
if not ok:
detail = '全部转换失败: ' + '; '.join(f'{u}: {e}' for u, e in failed)
raise HTTPException(status_code=500, detail=detail)
if failed:
(workdir / '_失败列表.txt').write_text(
'\n'.join(f'{u}\t{e}' for u, e in failed), encoding='utf-8'
)
background.add_task(shutil.rmtree, workdir, True)
# 单个任务:直接返回 PDF,保持单文件体验
if len(req.items) == 1 and not failed:
path = ok[0][1]
return FileResponse(path, media_type='application/pdf', filename=path.name)
# 多个任务:打包 zip
zip_path = workdir / f'html2pdf-{datetime.now():%Y%m%d-%H%M%S}.zip'
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for f in sorted(workdir.iterdir()):
if f != zip_path:
zf.write(f, f.name)
return FileResponse(zip_path, media_type='application/zip', filename=zip_path.name)
# 生产模式:托管前端构建产物(存在 frontend/dist 时)
dist = Path(__file__).parent / 'frontend' / 'dist'
if dist.is_dir():
app.mount('/', StaticFiles(directory=dist, html=True), name='frontend')
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='127.0.0.1', port=8000)