You need to enable JavaScript to run this app. Flask项目使用PyInstaller打包后无法加载运行时新增图片如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目使用PyInstaller打包后无法加载运行时新增图片如何解决?

问题根因与解决方案

根因分析

  • 你当前配置里把static/images加入了PyInstaller的datas列表,打包时该目录下的所有文件会被内置到程序包中,运行时(尤其是单文件模式)会被解压到临时目录,程序默认读的是这个临时目录下的文件,打包后新增的图片不会同步到这个临时目录,所以加载不到
  • 代码中使用相对路径static/images读取文件,PyInstaller运行时的工作目录和开发时的项目目录不一致,相对路径寻址会出错

具体解决方案

步骤1:拆分静态资源目录

将固定资源(模板、全局CSS/JS)和动态可新增的图片拆分:

  • 内置静态资源(templates、固定静态文件)依然走PyInstaller打包
  • 动态图片单独存放在exe运行目录下的独立文件夹,比如命名为user_images,该目录不加入打包配置

步骤2:修正代码中的路径逻辑

新增路径适配逻辑,兼容开发环境和PyInstaller打包后的运行环境,同时新增动态图片访问路由,修改后的后端代码示例:

import os
import sys
from flask import Flask, render_template, send_from_directory

app = Flask(__name__)
image_no_ = 0

# 获取基础路径:适配开发环境和PyInstaller打包环境
def get_base_path():
    if getattr(sys, 'frozen', False):
        # 打包后运行环境
        return sys._MEIPASS
    # 开发环境
    return os.path.abspath(".")

# 获取动态图片存储路径:和exe同目录的user_images文件夹
def get_user_image_path():
    if getattr(sys, 'frozen', False):
        # 打包后取exe所在目录
        exe_dir = os.path.dirname(sys.executable)
        image_dir = os.path.join(exe_dir, "user_images")
    else:
        # 开发环境用项目下的user_images目录
        image_dir = os.path.join(os.path.abspath("."), "user_images")
    # 目录不存在则自动创建
    if not os.path.exists(image_dir):
        os.makedirs(image_dir)
    return image_dir

# 新增动态图片访问路由
@app.route('/user_images/<filename>')
def serve_user_image(filename):
    return send_from_directory(get_user_image_path(), filename)

@app.route('/', methods = ['POST', 'GET'])
def show_image():
    global image_no_
    image_dir = get_user_image_path()
    files = os.listdir(image_dir)
    if not files:
        return "无可用图片"
    # 循环读取图片
    current_image = files[image_no_]
    image_no_ = (image_no_ + 1) % len(files)
    return render_template("index.html", image=current_image)  

if __name__=='__main__':
    # 开发模式下指定template_folder路径,打包后会自动读_MEIPASS下的templates
    app.run(debug=True, host='127.0.0.1', port=8000,
            template_folder=os.path.join(get_base_path(), "templates"))

步骤3:修改前端模板

将图片路径改为调用自定义的动态图片路由:

<html>
<head>
</head>
   
<body>
    <h1>Output page</h1>
    <img id="im" src="{{ url_for('serve_user_image', filename=image) }}" />
</body>
<script>
    var img = document.getElementById('im');
    console.log('img.src: ' + img.src);
</script>
</html>

步骤4:修改PyInstaller的spec配置

删除datas中static/images的配置,仅保留templates的打包配置即可:

# -*- mode: python ; coding: utf-8 -*-
block_cipher = None

a = Analysis(['test.py'],
             pathex=['/home/danish/Downloads/danish/code/TestFlask'],
             binaries=[],
             datas=[('templates/index.html', 'templates/')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='test',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True )

验证方式

打包完成后,在生成的exe文件同级目录下新建user_images文件夹,将需要展示的图片放入该文件夹即可,后续新增图片直接放入该目录即可正常加载,无需重新打包。


内容的提问来源于stack exchange,提问作者danishansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 07:27:02