Django - 安裝 WhiteNoise
WhiteNoise
Django 在生產環境中並沒有內建的解決方案來提供靜態檔案服務,尤其是在 DEBUG
設定為 False
的情況下。
我們需要使用第三方解決方案來實現這一功能。
在本教程中,我們將使用 WhiteNoise,這是一個為提供靜態檔案而構建的 Python 庫。
安裝 WhiteNoise
要在您的虛擬環境中安裝 WhiteNoise,請鍵入以下命令:
pip install whitenoise
結果應該類似於:
Collecting whitenoise
Downloading whitenoise-6.2.0-py3-none-any.whl (19 kB)
Installing collected packages: whitenoise
Successfully installed whitenoise-6.2.0
WARNING: You are using pip version 20.2.3; however, version 22.3.1 is available.
You should consider upgrading via the 'c:\users\Your Name\myworld\scripts\python.exe -m pip install --upgrade pip' command.
修改設定
為了讓 Django 知道您想執行 WhiteNoise,您必須在 settings.py
檔案的 MIDDLEWARE
列表中進行配置。
my_tennis_club/my_tennis_club/settings.py
:
.
.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
].
.
收集靜態檔案
在您能夠提供上一章示例中的靜態檔案之前,還需要執行一個操作。您必須收集所有靜態檔案並將它們放入一個指定的資料夾。您將在下一章中學習如何操作。