Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Angular4 + Django1.11 vol.11

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/

Backend Image Path

  • heroku上のbackendのimageのpathを設定する。

  • Video modelにimage_pathを追記する。

class Video(models.Model):
    name            = models.CharField(max_length=220)
    slug            = models.SlugField(unique=True, blank=True)
    embed           = models.CharField(max_length=120, help_text='Youtube Embed Code', null=True, blank=True)
    image_path      = models.CharField(max_length=120,blank=True, default='')
    active          = models.BooleanField(default=True)
    featured        = models.BooleanField(default=False)
    timestamp       = models.DateTimeField(auto_now_add=True)
  • herokuにdeployする。
$ git add .
$ git commit -m "comment"
$ git push heroku master && heroku run python manage.py migrate

Custom Domain Name

  • herokuでcustom domainを使う。以下の動画を参照して設定。

https://www.codingforentrepreneurs.com/projects/angular-django/custom-domain-name/?play=true#lecture

AWS S3 For Static Files in Django

{
"Version": "2012-10-17",
"Statement": [
 {
     "Effect": "Allow",
     "Action": [
         "s3:ListAllMyBuckets"
     ],
     "Resource": "arn:aws:s3:::*"
 },
 {
     "Effect": "Allow",
     "Action": [
         "s3:ListBucket",
         "s3:GetBucketLocation",
         "s3:ListBucketMultipartUploads",
         "s3:ListBucketVersions"
     ],
     "Resource": "arn:aws:s3:::<your_bucket_name>"
 },
 {
     "Effect": "Allow",
     "Action": [
         "s3:*Object*",
         "s3:ListMultipartUploadParts",
         "s3:AbortMultipartUpload"
     ],
     "Resource": "arn:aws:s3:::<your_bucket_name>/*"
 }
]
}
  • IAM > User > 権限を与えたいuserを選択 > アクセス権限の付与 > 作成したポリシーを選択

  • これで一旦、AWS側の設定は終了。

  • S3に必要なpython moduleをinstallする。

$ pip install boto3 django-storages
$ pip freeze > requirements.txt
  • 'storages'を, settings.pyに追記する。
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'storages',
    'videos',
]
  • src/tryangular/aws フォルダを作成する。また、__init__.pyを作成するのも忘れない。

  • src/tryangular/aws に、conf.py, utils.pyを作成する。

  • utils.pyには、static, mediaのファイルの保存設定を書く。

from storages.backends.s3boto3 import S3Boto3Storage'

StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static')
MediaRootS3BotoStorage  = lambda: S3Boto3Storage(location='media')
  • conf.pyには、以下のテンプレでコードを書く。
import datetime
AWS_ACCESS_KEY_ID = "<your_access_key_id>"
AWS_SECRET_ACCESS_KEY = "<your_secret_access_key>"
AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True

DEFAULT_FILE_STORAGE = '<your-project>.aws.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = '<your-project>.aws.utils.StaticRootS3BotoStorage'
AWS_STORAGE_BUCKET_NAME = '<your_bucket_name>'
S3DIRECT_REGION = 'us-west-2'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

two_months = datetime.timedelta(days=61)
date_two_months_later = datetime.date.today() + two_months
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")

AWS_HEADERS = {
 'Expires': expires,
 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
}
  • local.pyに、conf.pyを読み込むように設定する。
...
from tryangular.aws.conf import *
  • まずlocalで、python manage.py collectstaticを試してみる、、、成功!

  • 次に、production環境でも,S3を使うように設定していく。

  • production.pyの、STATICFILES_STORAGEの設定をコメントアウトする。

# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
  • wsgi.py のwhitenoiseの設定の箇所を削除する。
import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()
  • $pip uninstall whitenoiseで、whitenoiseをuninstallする。

  • herokuは、自動でcollectstaticしないように、collectstaticを禁止するコマンドを入れる。

$ heroku config:set DISABLE_COLLECTSTATIC=1
  • herokuにデプロイして、現時点では、imageが、うまく表示されていないと思うので、それでOK。

まとめ

  • projectごとに、awsのuserは分けよう。