部署 Heroku 筆記(非步驟) - josephsiao/mini-blog GitHub Wiki
專案根目錄建立 Procfile
檔案 (無副檔名, UTF-8 編碼)
web: gunicorn --pythonpath 專案名稱 專案名稱.wsgi --log-file -
安裝額外所需套件
gunicorn
django-heroku
dj-database-url
psycopg2-binary
whitenoise
將已安裝套件輸出在根目錄建立 requirements.txt
$ pip freeze > requirements.txt
在根目錄建立 runtime.txt
輸入 python 執行版本 (例如 3.6.8)
python-3.6.8
登入 Heroku
$ heroku open
推送 Heroku
$ git push heroku master
開啟網站
$ heroku open
設定環境變數
設定 DJANGO_SECRET_KEY
$ heroku config:set DJANGO_SECRET_KEY='你的 Django SECRET KEY'
啟用一個 Dyno 執行 web 服務
$ heroku ps:scale web=1
清空 Heroku Repository
必須安裝 plugin
$ heroku plugins:install heroku-repo
清空
$ heroku repo:reset
重設資料庫
$ heroku pg:reset
資料庫資訊
$ heroku pg:info
makemigrations
需在本地執行後再提交到 Heroku, 然後進行 migrate
$ heroku run python 專案名稱/manage.py migrate
新增與修改 settings.py
import dj_database_url
import django_heroku
SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # 改為讀取環境變數
DEBUG = False # 更改為 False
ALLOWED_HOSTS = [
'YOUR APP NAME.herokuapp.com',
'herokuapp.com',
'localhost',
'127.0.0.1',
'[::1]'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # 在 security 下新增此行
...
...
...
]
# This tells Django to trust the X-Forwarded-Proto header that comes from our proxy, and any time its value is 'https', then the request is guaranteed to be secure
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# WhiteNoise comes with a storage backend which automatically takes care of compressing your files and creating unique names for each version so they can safely be cached forever.
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DATABASES = {
'default': dj_database_url.config(conn_max_age=600)
}
# Activate Django-Heroku.
django_heroku.settings(locals())
或是不修改 settings.py
而是在 settings.py
的資料夾內另外建立 production_settings.py
(未嘗試過)
再設定 Heroku 環境變數
$ heroku config:set DJANGO_SETTINGS_MODULE=專案名稱.production_settings
requirements.txt
包含套件如下
asgiref==3.2.7
astroid==2.4.0
bleach==3.1.4
colorama==0.4.3
dj-database-url==0.5.0
Django==3.0.5
django-bleach==0.6.1
django-ckeditor==5.9.0
django-heroku==0.3.1
django-js-asset==1.2.2
entrypoints==0.3
flake8==3.7.9
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
psycopg2==2.8.5
psycopg2-binary==2.8.5
pycodestyle==2.5.0
pyflakes==2.1.1
pylint==2.5.0
pylint-django==2.0.15
pylint-plugin-utils==0.6
pytz==2019.3
six==1.14.0
sqlparse==0.3.1
toml==0.10.0
typed-ast==1.4.1
webencodings==0.5.1
whitenoise==5.0.1
wrapt==1.12.1
References
Django Tutorial Part 11: Deploying Django to production
Deploying Django App on Heroku with Postgres as Backend
2018-08-17[Python+Django]初心者筆記15(發行應用程式,Deploying Django to production)