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