flask示例代码
import os
import sys
from flask import Flask, render_template
from flask_cors import CORS
# 获取资源路径
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
app = Flask(__name__, static_url_path="", static_folder=resource_path('static'),
template_folder=resource_path("templates"))
# 允许全局跨域配置
CORS(app, supports_credentials=True)
@app.route('/')
def index():
return render_template('index.html')
app.run()
pyinstaller打包示例代码
from PyInstaller.__main__ import run
if __name__ == '__main__':
opts = ['main.py', # 主程序文件
'-n flask', # 可执行文件名称
'-F', # 打包单文件
# '-w', #是否以控制台黑窗口运行
r'--icon=E:/图标/leaves_16px_1218386_easyicon.net.ico', # 可执行程序图标
'-y',
'--clean',
'--workpath=build',
'--add-data=templates;templates', # 打包包含的html页面
'--add-data=static;static', # 打包包含的静态资源
'--distpath=build',
'--specpath=./'
]
run(opts)
执行这段打包代码即可。templates
目录放置的是html模板文件,static
目录放置的是静态资源。具体目录和路径等配置根据自己项目调整。
运行结果示例:
本示例使用的是anaconda环境中的python 3.7,如果使用单独安装的python环境,打包体积会小一些。
注意
pyinstaller打包代码执行之前要确保pyinstaller已经正确安装,一般pip install pyinstaller
即可正常安装pyinstaller。
参考资料
pyinstaller参考配置官网地址:https://pyinstaller.readthedocs.io/en/stable/usage.html#options