K-Digital Training(ビッグデータ)11日目


今日awsでdb設定とログイン機能をしました.
  • forms.py
  • from django.contrib.auth.models import User
    from django import forms
    
    
    class RegisterForm(forms.ModelForm):
        password = forms.CharField(label='Password', widget=forms.PasswordInput)
        password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
    
        class Meta:
            model = User
            fields = ['username', 'first_name', 'last_name', 'email']  # 필드이름은 정해져있다
    
        def clean_password2(self):
            cd = self.cleaned_data
            if cd['password'] != cd['password2']:
                raise forms.ValidationError('패스워드가 일치하지 않습니다.')
            return cd['password2']
    
  • views.py
  • from django.shortcuts import render
    from .forms import RegisterForm
    
    def register(request):
        if request.method == 'POST':
            user_form = RegisterForm(request.POST)
            if user_form.is_valid():#값이 있을 때 만
                new_user = user_form.save(commit=False)
                new_user.set_password(user_form.cleaned_data['password'])
                new_user.save()#문제없으면 save
                return render(request, 'registration/register_done.html', {'new_user':new_user})
        else:
            user_form = RegisterForm()
    
        return render(request, 'registration/register.html', {'form':user_form})
  • accounts/urls.py
  • from .views import register
    path('register/', register, name='register')
  • register.html
  • {% extends 'base.html' %}
    
    {% block title %}
        - Signup
    {% endblock %}
    
    {% block content %}
            <div class="row my-5">
             <div class="row">
                <div class="col-12 panel panel-default">
                <div class="alert alert-info">
                    회원가입
                </div>
                    <form action="" method="post">
                        {% csrf_token %}
                        {{ form.as_p }}
                        <input type="submit" class="btn btn-primary" value="등록">
                    </form>
                </div>
            </div>
        </div>
    
    {% endblock %}
    
    
    register_done.html
    
    {% extends 'base.html' %}
    
    {% block title %}
        - 회원가입 축하합니다!
    {% endblock %}
    
    {% block content %}
            <div class="row my-5">
             <div class="row">
                <div class="col-12 panel panel-default">
                <div class="alert alert-info">
                    어서오세요 ~ 회원가입 축하합니다!
                </div>
                   <a class="btn btn-info" href="/">Move to Main</a>
                </div>
            </div>
        </div>
    
    {% endblock %}
  • base.htmlにSignupページ
  • を接続する
    # S3를 사용할 수 있는 곳
    # 1. Static
    
    AWS_ACCESS_KEY_ID = 'AKIAXEABGLSEPCA6BCMY'#키값(access키)
    AWS_SECRET_ACCESS_KEY = 'BqV+FqEKr2gwR4WVs7KulDknNDIH0VtkQZ3NW/RO'#시크릿키
    AWS_REGION = 'ap-northeast-2'
    AWS_STORAGE_BUCKET_NAME = 'djangokd'
    
    AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % (AWS_STORAGE_BUCKET_NAME, AWS_REGION)
    
    AWS_S3_FILE_OVERWRITE = False
    AWS_S3_OBJECT_PARAMETERS = {
        'CacheControl':'max-age=86400',
    }
    AWS_DEFAULT_ACL = 'public-read'
    AWS_LOCATION = 'static'
    
    STATIC_URL = 'http://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    
    # MEDIA_URL = '/media/'
    # MEDIA_ROOT = os.path.join(BASE_DIR,'media')
    
    DEFAULT_FILE_STORAGE = 'config.s3media.MediaStorage'
    # Default primary key field type
    # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
    
    # DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
    pip install boto3
    pip install django-storages
  • settings.pyアプリケーション
  • に登録
  • python manage.py collectstatic(ライブラリ内のすべてのstticファイルを転送)
    -yes
    パケットに入り、静的にデータがある場合、通常
  • settings.py
  • """
    Django settings for config project.
    
    Generated by 'django-admin startproject' using Django 3.2.6.
    
    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 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-x8g9444lshhx2*#39s4t*#$69)y2mu9!tle*idvqa!!remzen^'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'photo',
        'accounts',
        'django.contrib.sites',
        'storages',
    
    ]
    
    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',
    ]
    
    ROOT_URLCONF = 'config.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, "templates")],
            '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 = 'config.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',
        }
    }
    
    # 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 = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    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/'
    
    # Default primary key field type
    # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
    
    #DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  • config/s3.media.pyファイル
  • の作成
    from storages.backends.s3boto3 import S3Boto3Storage
    
    class MediaStorage(S3Boto3Storage):
        location = 'media'
        file_overwrite = False
    10 . アマゾン
    アマゾンに接続
    aws管理コンソール(ソウル)
    S 3->パケットの作成->名前->
    無効化(選択解除)->すべての共通をチェック->作成
  • 証明書
  • を取得
    IAM
    ユーザーの追加->名前の入力->アクセスプログラミング->グループの作成->
    s 3->fullaccess->グループ名の検索->タグは任意->作成->キー値の受け入れ
  • settings.pyにawsコード
  • を書き込む
  • データベース
  • の作成
    aws->rds->パラメータグループ->作成->mysql 8.0->名前の書き込み->作成
    データベースの作成->MySQL->Pretier->識別子名->パスワード->
    自動調整の無効化
    新規->セキュリティグループ名
    その他の構成->名前->グループの選択->自動バックアップしない->マネージャxの作成->
    識別子->vpcセキュリティグループ->インバウンド->インバウンドの編集->カスタム->any->保存
  • WORKBENCH取付
  • Workbench->ダウンロード->インストール
    db詳細->修正->接続->その他の構成->アクセス可能->修正->即時適用->
    エンドポイント->ワークベンチ->+>hostname:エンドポイント/username:id/pass:番号付けなし
    なんてことだ
    新しいアプリケーションの作成(ショッピング)

  • pip install django

  • django-admin startproject config .

  • pip install pymysql

  • settings.py
  • import pymysql
    pymysql.install_as_MySQLdb()
    
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'djangodatab',
            'USER': 'admin',
            'PASSWORD': 'dbgusals1',
            'HOST': 'django.c6f9olbkzmcs.ap-northeast-2.rds.amazonaws.com',
            'PORT': '3306'
        }
    }#데이터베이스 이름 적는다, host는 엔드포인트

  • python manage.py migrate

  • python manage.py createsuperuser
  • config/settings.py
  • # S3를 사용할 수 있는 곳
    # 1. Static
    
    AWS_ACCESS_KEY_ID = ''
    AWS_SECRET_ACCESS_KEY = ''
    AWS_REGION = 'ap-northeast-2'
    AWS_STORAGE_BUCKET_NAME = ''
    
    AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % (AWS_STORAGE_BUCKET_NAME, AWS_REGION)
    
    AWS_S3_FILE_OVERWRITE = False
    AWS_S3_OBJECT_PARAMETERS = {
        'CacheControl':'max-age=86400',
    }
    AWS_DEFAULT_ACL = 'public-read'
    AWS_LOCATION = 'static'
    
    STATIC_URL = 'http://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    DEFAULT_FILE_STORAGE = 'config.s3media.MediaStorage'
  • pip install boto3
  • settings.py
  • 'storages',

  • pip install django-storages

  • python manage.py collectstatic

  • パケットの確認

  • config/settings.py
  • DEFAULT_FILE_STORAGE = 'config.asset_storage.MediaStorage'
  • asset_storage.py作成
  • from storages.backends.s3boto3 import S3Boto3Storage
    
    
    class MediaStorage(S3Boto3Storage):
        location = 'media'
        file_overwrite = False
  • アプリケーションの作成
    python manage.py startapp shop
  • settings.pyにshop
  • を追加
  • shop/models.py
  • from django.db import models
    
    from django.urls import reverse
    
    
    class Category(models.Model):
        name = models.CharField(max_length=200, db_index=True)
        meta_description = models.TextField(blank=True)  # 설명문
    
        slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)  # unicode = 한글 안꺠지게
    
        class Meta:
            ordering = ['name']  # 정렬
            verbose_name = 'category'  # 어드민에 표시될때 필요한 내용
            verbose_name_plural = 'categories'
    
        def __str__(self):
            return self.name
    
        def get_absolute_url(self):
            return reverse('shop:product_in_category', args=[self.slug])
    
    
    class Product(models.Model):
        category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products')
        name = models.CharField(max_length=200, db_index=True)
        slug = models.SlugField(max_length=200, db_index=True, unique=True, allow_unicode=True)  # unicode = 한글 안꺠지게
    
        image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
        description = models.TextField(blank=True)
        meta_description = models.TextField(blank=True)
    
        price = models.PositiveIntegerField()
        sale = models.PositiveIntegerField()
    
        available_display = models.BooleanField('Display', default=True)
        available_order = models.BooleanField('Order', default=True)
    
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
    
        class Meta:
            ordering = ['-created']
            index_together = [['id', 'slug']]
    
        def __str__(self):
            return self.name
    
        def get_absolute_url(self):
            return reverse('shop:product_detail', args=[self.id, self.slug])

  • pip install pillow

  • python manage.py makemigrations

  • python manage.py migrate