Django - Heroku部屬

講師:Arashi

日期:2020/05/24

Outline

  • 套件安裝

  • 設定部屬環境

  • Heroku

  • 參考資源

套件安裝

$ pip install dj-database-url gunicorn dj-static psycopg2-binary
  •  dj-database-url
    • 支援 PostgreSQL, PostGIS, MySQL等資料庫
    • 收集所有在你的URL指定的數據
  •  gunicorn
    • 能夠與各種wsgi web框架協作
  •  dj-staic
    • 讓我們可以使用 staic
  •  psycopg2-binary
    • 用於操作 PostgreSQL
$ pip freeze > requirements.txt

將有用到的套件都寫入 requirements.txt

asgiref==3.2.7
dj-database-url==0.5.0
dj-static==0.0.6
Django==3.0.6
gunicorn==20.0.4
Pillow==7.1.2
pytz==2020.1
sqlparse==0.3.1
static3==0.7.0
psycopg2==2.8.5

$ pip install -r requirements.txt

設定部屬環境

Procfile

啟用名為 web 的應用,並以 gunicorn 來 執行 mysite.wsgi 模組

web: gunicorn --pythonpath mysite mysite.wsgi

mysite/mysite/production_settings.py

# Import all default settings.
from .settings import *
import dj_database_url

DATABASES = {
    'default': dj_database_url.config(),
}

# Static asset configuration.
STATIC_ROOT = 'staticfiles'

# Honor the 'X-Forwarded-Proto' header for request.is_secure().
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers.
ALLOWED_HOSTS = ['*']

# Turn off DEBUG mode.
DEBUG = False

建立專門給部屬環境的設定

mysite/mysite/wsgi.py

import os

from django.core.wsgi import get_wsgi_application

from dj_static import Cling

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = Cling(get_wsgi_application())

定義 Heroku 和我們網站溝通的介面

.gitignore

venv
*.pyc
__pycache__
staticfiles
db.sqlite3

不希望讓他人得知,或是不必要部屬上伺服器的檔案名稱都寫入此文件黨內

Heroku

一種支援多種程式語言的平台既服務

Heroku

創建 APP

$ heroku login
$ heroku create appname
$ heroku apps

如果已經在網頁版有登入, heroku login 會跳至網頁版頁面直接讓你按登入,否則要在 cmd 輸入帳密。

appname 放想取的 app名稱,也可以不放,則會隨機產生一個名稱。

上傳

初始化 git
$ git init

將專案指定給剛創立的app
$ heroku git:remote -a appname

設定環境變數
heroku config:set 變數名稱 = 變數內容
$ heroku config:set DJANGO_SETTINGS_MODULE=mysite.production_settings

上傳

$ git add .
$ git commit -m "message"
$ git push heroku master

初始化網站

$ heroku ps:scale web=1
$ heroku run python mysite/manage.py migrate
$ heroku run python mysite/manage.py createsuperuser
$ heroku open

參考資源

Thanks for listening

Django - heroku部屬

By arashi

Django - heroku部屬

  • 140