第 14 章    部署專案

▸ 安裝 django-toolbelt

(blogVenv)$ pip install django-toolbelt

▸ 新增三個檔案:

Procfile
web: gunicorn blog.wsgi --log-file -
requirements.txt
dj-database-url==...
dj-static==...
Django==...
django-toolbelt==...
gunicorn==...
psycopg2==...
pytz==...
sqlparse==...
static3==...
runtime.txt
python-3.7.6

▸ 修改設定檔

blog/settings.py
...
DEBUG = True
if 'DYNO' in os.environ:    # Running on Heroku
    DEBUG = False

...

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

if DEBUG:   # Running on the development environment
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'blogdb',
            'USER': 'dbuser',
            'PASSWORD': 'dbuser',
            'HOST': 'localhost',
            'PORT': '',     # Set to empty string for default.
        }
    }
else:   # Running on Heroku
    # Parse database configuration from $DATABASE_URL
    import dj_database_url
    DATABASES = {'default':dj_database_url.config()}
    # Honor the 'X-Forwarded-Proto' header for request.is_secure()
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

...

LOGIN_URL = '/account/login/'

# For Heroku deployment
STATIC_ROOT = 'staticfiles'

▸ 修改 wsgi 檔

blog/wsgi.py
...

application = get_wsgi_application()

from blog.settings import DEBUG
if not DEBUG:    # Running on Heroku
    from dj_static import Cling
    application = Cling(get_wsgi_application())

▸ 在 Ubuntu 安裝 Heroku CLI

$ sudo snap install --classic heroku

▸ 在 Mac 安裝 Heroku CLI

$ brew tap heroku/brew && brew install heroku

▸ 部署填充程式

populate/production.py
from populate import base
from account.models import User

print('Creating admin account ... ', end='')
User.objects.create_superuser(username='admin', password='????????', email=None, fullName='管理者')
print('done')

▸ 將遷移檔納入版本控制

.gitignore
*~
__pycahe__
*.pyc
00*.py

▸ 本章完成專案:blog14.zip