在Heroku上发布Django的网页服务的过程
以非常迅速的速度做好环境准备。
创建目录
创建一个目录,用于创建Django项目。
$ mkdir testproject
$ cd testproject
搭建虚拟环境并安装Django。
如果使用Python3.6或更高版本,您可以使用Python命令创建虚拟环境。这次我们将创建一个名为venv的虚拟环境。
$ python -m venv venv
$ source venv/bin/activate
$ pip install django
$ django-admin version
※如果你使用的是Windows系统,请尝试运行source venv/Scripts/activate,而不是source venv/bin/activate。
创建项目
当您确认 Django 版本后,我们将创建项目。
$ django-admin startproject testproject
$ cd testproject
$ python manage.py startapp testapp
在拥有testapp文件夹的目录层级中,我将暂时创建两个文件夹和一个文件。
$ mkdir static
$ cd static
$ touch style.css
$ cd ../
$ mkdir templates
$ cd templates
$ touch index.html
文件结构
testproject
├── db.sqlite3
├── manage.py
├── static
│   └── style.css
├── templates
│   ├── index.html
├── testapp
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── testproject
    ├── local_settings.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
Heroku 安装
$ brew tap heroku/brew && brew install heroku
如果是Windows用户,请点击此处下载安装 https://devcenter.heroku.com/articles/heroku-cli#download-and-install
接下来,我们将使用以下命令在Heroku上安装Django所需的模块。
$ pip install gunicorn whitenoise django-heroku dj-database-url
创建heroku启动所需的文件。
$ echo web: gunicorn testproject.wsgi --log-file - > Procfile
$ pip freeze > requirements.txt
$ python -V
当Python版本出现时,请将其记录下来。
$ echo python-3.8.8 > runtime.txt
在Git中指定不受管理的文件。(.gitignore)
$ echo -e __pycache__\\ndb.sqlite3\\n.DS_Store\\nlocal_settings.py > .gitignore
在与settings.py相同的目录下创建一个名为local_settings.py的文件,并按照以下内容进行添加。
import os
#settings.pyからそのままコピー
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = '**************************' # settings.py から該当部分コピー
#settings.pyからそのままコピー
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
DEBUG = True
修改其他需要编辑的文件如下。
"""
Django settings for testproject project.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import dj_database_url
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = 'django-insecure-w3v(******************)@**********************
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'testapp' # 追加部分
]
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', # 追加部分
]
ROOT_URLCONF = 'testproject.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'testproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name',
        'USER': 'user',
        'PASSWORD': '',
        'HOST': 'host',
        'PORT': '',
    }
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
try:
    from .local_settings import *
except ImportError:
    pass
if not DEBUG:
    SECRET_KEY = os.environ['SECRET_KEY']
    import django_heroku
    django_heroku.settings(locals())
db_from_env = dj_database_url.config(conn_max_age=600, ssl_require=True)
DATABASES['default'].update(db_from_env)
将应用程序上传至Heroku
首先,请先在Heroku上完成新用户注册。
https://heroku.com
$ git init
$ git add -A
$ git commit -m "initial commit"
$ heroku login
$ heroku create <***herokuプロジェクト***>
将`settings.py`中的`SECRET_KEY`进行填写。
$ heroku config:set SECRET_KEY='**************************'
$ git push heroku master
$ heroku ps:scale web=1
最后,进行迁移并启动Heroku。
$ heroku run python manage.py migrate
$ heroku run python manage.py createsuperuser
$ heroku open
YouTube: 用 Django 开发 LINE 聊天机器人
YouTube: 在 Heroku 上发布 Django 的 Web 服务
 
    