Skip to content

Commit 90835c7

Browse files
author
User
committed
fix: 修复 PyInstaller 打包资源文件问题
- 添加 templates 和 static 目录到打包 - 添加更多 hidden imports - 修复 Flask 资源路径,兼容 PyInstaller
1 parent 287963e commit 90835c7

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

build_backend.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,26 @@ def build():
3737
"--distpath", output_dir,
3838
"--workpath", os.path.join(script_dir, "build", "pyinstaller"),
3939
"--specpath", os.path.join(script_dir, "build"),
40+
# Include data files
41+
"--add-data", f"{os.path.join(script_dir, 'templates')}{os.pathsep}templates",
42+
"--add-data", f"{os.path.join(script_dir, 'static')}{os.pathsep}static",
4043
# Hidden imports
4144
"--hidden-import", "flask",
4245
"--hidden-import", "flask_cors",
4346
"--hidden-import", "requests",
4447
"--hidden-import", "bs4",
4548
"--hidden-import", "lxml",
49+
"--hidden-import", "lxml.html",
50+
"--hidden-import", "lxml.etree",
4651
"--hidden-import", "werkzeug",
4752
"--hidden-import", "jinja2",
4853
"--hidden-import", "markupsafe",
4954
"--hidden-import", "itsdangerous",
5055
"--hidden-import", "click",
56+
"--hidden-import", "html2text",
57+
"--hidden-import", "xhtml2pdf",
58+
"--hidden-import", "reportlab",
59+
"--hidden-import", "ebooklib",
5160
# Main program
5261
os.path.join(script_dir, "web_app.py")
5362
]

web_app.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,24 @@
1414
from flask import Flask, render_template, request, jsonify, send_from_directory
1515
from flask_cors import CORS
1616

17+
# PyInstaller 打包后的资源路径处理
18+
def get_resource_path(relative_path):
19+
"""获取资源文件的绝对路径,兼容 PyInstaller 打包"""
20+
if hasattr(sys, '_MEIPASS'):
21+
# PyInstaller 打包后的临时目录
22+
return os.path.join(sys._MEIPASS, relative_path)
23+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)
24+
1725
# 添加当前目录到路径
18-
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26+
if hasattr(sys, '_MEIPASS'):
27+
sys.path.insert(0, sys._MEIPASS)
28+
else:
29+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
1930

20-
app = Flask(__name__, static_folder='static', template_folder='templates')
31+
# Flask 应用初始化
32+
template_folder = get_resource_path('templates')
33+
static_folder = get_resource_path('static')
34+
app = Flask(__name__, static_folder=static_folder, template_folder=template_folder)
2135
CORS(app)
2236

2337
# 全局状态

0 commit comments

Comments
 (0)