Angular4 + Django1.11 vol.10
参考サイト
https://www.codingforentrepreneurs.com/projects/angular-django/
Go Live with Heroku, Django, & Angular
heroku へのdeployの準備をする。
settings.pyのコードの修正をする。
# settingsフォルダを作成して、その中に、settingsファイルを設定するため、BASE_DIRの階層を1つ深くしておく。
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
tryangular/settings フォルダを作成する。
settingsフォルダ内に,
__init__.py
,base.py
,local.py
,production.py
を作成する。__init__.py
にコードを追記する。
from .base import * from .production import *
production.py
にdeploy用の設定を書いていく。まず、Emailの設定をする。
# EMAILの設定 EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = '*************' # sendgridのuser EMAIL_HOST_PASSWORD = '*************' # sendgridのpass EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Your Name <you@email.com>' ADMINS = ( ('You', 'you@email.com') ) MANAGERS = ADMINS
- herokuのdeployに必要なmoduleをpip installする。
$ pip install dj-database-url dj-static django-toolbelt gunicorn psycopg2 static3
- requirements.txtを作成する。
$ pip freeze > requirements.txt
- .gitignoreファイルをbackend/src内に作成する。(.gitignoreは、djangoデプロイ用と、djangular4プロジェクト全体を分けておく)
.DS_Store client/node_modules client/e2e client/bootstrap-overview tryangular/settings/local.py backend/bin backend/include backend/lib # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # compiled output /dist /tmp /out-tsc # dependencies /node_modules # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log testem.log /typings # e2e /e2e/*.js /e2e/*.map # System Files .DS_Store Thumbs.db
- Procfileを、backend/src内に作成する。
web: gunicorn tryangular.wsgi --log-file -
- production.py にheroku用のdatabaseの設定を追記する。
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ## 以下を追記 import dj-database-url db_from_env = dj-database-url.config() DATABASES['default'].update(db_from_env)
- さらに, production.pyにSTATICFILES_STORAGEを設定する。
STATIC_URL = '/static/' # STATIC_ROOTをstaticherokuに変更する。 STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticheroku') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # STATICFILES_STORAGEを設定する。 STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryangular.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)
- テストで、
python manage.py runserver
してみると、error発生! whitenoiseをpip installしていないとのことなので、installする。
$ pip install whitenoise $ pip freeze > requirements.txt
再度、
python manage.py runserver
を実行する。。。成功!$ python manage.py collectstatic
で、staticファイルを集める。。。。問題発生。backend/src/staticherokuにcollectstaticしたいが、現状では、backend/staticheroku にコピーされてしまっている。settings.pyの、STATIC_ROOTの設定が間違っているので、修正する。production.pyの方を修正する。
STATIC_ROOT = os.path.join(BASE_DIR, 'staticheroku')
src/tryangular/settings/__init.py
にlocal.pyについてのコードを追記する。
from .base import * from .production import * try: from .local import * except: pass
heroku のrepositoryを
$ heroku create tryangular-djangoroid
コマンドで作成する。$ git remote -v
で、gitのremoteの状態がわかる。別のrepositoryを参照にしてある場合は、$git remote remove heroku
で削除できる。$git init
して、$ git remote add heroku https://git.heroku.com/tryangular-djangoroid.git
で、さっきcreateしたrepositoryに、remote addできる。
$ git init $ git remote add heroku https://git.heroku.com/tryangular-djangoroid.git
- git remoteの状態を確認する。
$ git remote -v heroku https://git.heroku.com/tryangular-djangoroid.git (fetch) heroku https://git.heroku.com/tryangular-djangoroid.git (push)
- 以下の手順で、herokuにdeployする。
$ git add --All $ git commit -m "first commit" $ git push heroku master
- とりあえず、デプロイはうまくいった!!サイトにアクセスしてみる。。。。error!
DisallowedHost at / Invalid HTTP_HOST header: 'tryangular-djangoroid.herokuapp.com'. You may need to add u'tryangular-djangoroid.herokuapp.com' to ALLOWED_HOSTS.
- production.pyの、ALLOWED_HOSTSを修正する。
ALLOWED_HOSTS = ['tryangular-djangoroid.herokuapp.com', '.herokuapp.com']
- runtime.txt で、pythonのversionを指定できるので、作成しておく。
python-3.4.3
- heroku repositoryに、postgresのaddonを追加する。
$ heroku addons:create heroku-postgresql:hobby-dev
$ git push heroku master && heroku run python manage.py migrate
を実行してみる。。。error!
remote: -----> Installing python-3.4.3 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory
上記はたぶん、3.4.3にherokuが対応してないぽいerrorな気がする。。。ので、runtime.txt を、
python-3.6.0
に変更して、再度デプロイしてみる。。。できた〜〜〜!!(^^)$ heroku run python manage.py createsuperuser
で, superuserを作成する。https://tryangular-djangoroid.herokuapp.com/
にアクセスしてみる、、、できた〜〜!!
まとめ
- やっぱheroku便利やなぁw