pyinstaller打包django專案

2021-08-25 05:44:55 字數 1758 閱讀 2144

安裝pyinstaller

pip install pyinstaller
製作專案的.spec檔案

進入django專案所在路徑,執行

pyi-makespec -d manage.py
在路徑下,生成乙個.spec檔案

以文字的方式開啟.spec檔案,spec檔案格式如下。具體spec的使用,可以檢視官網

不修改.spec檔案,直接執行以下語句

pyinstaller manage.spec以上hiddenimports弄好後,執行後會出現以下的錯誤

templatedoesnotexist  這個是因為沒有找到templates檔案.

可以根據錯誤提示將templates檔案新增至對應的路徑下,重新整理即可。其中front是我工程下乙個放所有前端東西的檔案,templates是用來放html的乙個資料夾。(所以具體的新增要根據錯誤提示是在**找不到就新增至**)

在第五步後,可以發現頁面已經出來,但是發現頁面沒有css和js了

這是因為pyinstaller 能找到templates(html files檔案),但不能找到css和js檔案。

我的解決方案是參考了以下 :

我的具體操作是在django專案的settirngs.py檔案中加入

static_root = os.path.join(base_dir, 'front', 'static_root')

其中front是我的資料夾,static_root是我在front下建立的乙個空子檔案,用來收集工程中所有的靜態檔案。

在django專案路徑下執行manage.py collectstatic會自動地將staticfiles_dirs

from django.conf.urls import static

urlpatterns += static.static(settings.static_url, document_root=settings.static_root)

這句話的意思就是將static_root目錄的靜態檔案複製乙份到網頁 static_url路徑下

最後我們還需要將static_root中的靜態檔案打包到.exe中。這一步是在.spec檔案中的datas中加入下面乙個元組

datas=[(r'e:\g48\g48\front\static_root',r'.\front\static_root'), (r'e:\g48\g48\front\templates', r'.\front\templates')],
考慮到第5步,再這裡我也直接將templates檔案打包到了對應的檔案。所以第五步就不用自己再複製templates檔案到指定的資料夾了。

最後.spec檔案看起來如下:

一切準備好後,執行下面語句就ok

pyinstaller manage.spec
如果在專案中有多程序,可以參考以下

pyinstaller打包程式

python打包成exe檔案時,用的是pyinstaller 第一步安裝pyinstaller pip install pyinstaller第二步 pyinstaller f w i ico py其中 ico 是logo,py是你要打包的py檔案 我在打包時出現了struct.error unpa...

pyinstaller打包使用

pyinstaller manage.py 如果直接打包報錯,使用如下命令可以直接生成配置檔案 pyi makespec d manage.py生成的配置檔案格式如下 mode python coding utf 8 block cipher none a analysis impala etl.p...

pyinstaller 打包總結

pyinstaller 打包過程總結 安裝 pyinstaller 打包工具 pip3 install pyinstallerpyinstaller 打包命令不熟悉的小夥伴可點選這裡檢視喲 備註 以下涉及到的檔案名字main.py,請替換成自己的檔名 執行打包命令生成單獨的 exe 程式 pyins...