18. 01. 22~23

18. 01. 22

오늘 한 일

  • 노마드코더 인스타클론 코딩 백앤드의 요소

You need a backend if You want to save data

Django is very fast for developers

Secure

Handy - 편리해

프레임워크 vs 라이브러리

a library is a tool

Django has an ORM

Admin Panel

User Authentication

URL Dispatcher

Template Engine

pipenv 가상환경 만드는 법

  1. 프로젝트 디렉토리 생성 후
    • mkdir bsdir
    • cd bsdir
  2. pipenv 명령어로 가상환경 생성
    • pipenv —three
  3. 가상환경에 장고 설치
    • pipenv install django

가상환경에 개발환경을 설치하면 Pipfile이 생기는데 이 파일만 있으면 다른 컴퓨터에서도 그대로 가상환경을 구축가능하다. (이 파일에 어떤 환경이 설치되었는지 기록됨)

  1. 가상환경에 접속하는 법
    • pipenv shell
  2. 가상환경에서 장고 어드민 확인
    • django-admin
  3. 가상환경에서 나가기
    • exit

Parts of Django
Settings, Urls and Apps

Apps
Apps are what your application is made of Apps have a defined scope and they responsibilities are very precise A Django project can have as many apps as you want Try to keep your small app

Django Apps for an E-commerce
Products
Users
Cart
Payments

App: Products
Showing the products
Searching for a product
Leaving a review
Creating products (admin)

App: Users
Create account
Log in
Create a shopping cart
Add payment information
Leave reviews

App: Cart
User will create it
Update it
Delete it
Share it
Go to checkout

App: Payments
Payment method processing
Checking credit cards
Adding Automatic taxes
Handling refunds
Protecting CC data
Working with payment processors (PayPal, Stripe)

쿠키커터 설치
pip install cookiecutter(글로벌)

가상환경에 쿠키커터 설치
pipenv install cookiecutter
pipenv shell
cookiecutter https://github.com/pydanny/cookiecutter-django

쿠키커터로 장고 프로젝트 클론 후 셋팅

project_name [Project Name]: Nomadgram
project_slug [nomadgram]:
author_name [Daniel Roy Greenfeld]: Nomad Coders
email [you@example.com]: yesdoing@nomadcoders.co
description [A short description of the project.]: Cloning IG with Py
domain_name [example.com]: nomadcoders.co
version [0.1.0]:
timezone [UTC]: Asia/Seoul
use_whitenoise [y]: n
use_celery [n]:
use_mailhog [n]:
use_sentry_for_error_reporting [y]: n
use_opbeat [n]:
use_pycharm [n]:
windows [n]:
use_docker [n]:
use_heroku [n]:
use_compressor [n]:
Select postgresql_version:
1 - 10
2 - 9.6
3 - 9.5
4 - 9.4
5 - 9.3
6 - 9.2
Choose from 1, 2, 3, 4, 5, 6 [1]: 2
Select js_task_runner:
1 - Gulp
2 - Grunt
3 - None
Choose from 1, 2, 3 [1]: 3
custom_bootstrap_compilation [n]:
Select open_source_license:
1 - MIT
2 - BSD
3 - GPLv3
4 - Apache Software License 2.0
5 - Not open source
Choose from 1, 2, 3, 4, 5 [1]: 1

장고 프로젝트로 이동
cd nomadgram

코드로 열기
code .

필요없는 디렉토리 삭제
결과물 이미지

깃허브 등록

git init

git remote add origin {YOUR_GIHTUB_URL}
git pull origin master
git add .
git commit -m "First commmit"
git push origin master

Installing the requirements (프로젝트에 필요한 것들 설치)

pipenv —three
pipenv shell
pipenv install -r requirements/local.txt

Django에는 config라는 파일에 settings라는 설정파일이 존재한다.
여기서는 여러개의 파일이 존재하는데
base.py는 글로벌한 공통 설정파일(서버+로컬)
local.py는 로컬 (자기 컴퓨터의 설정파일)
production.py는 서버의 설정파일을 가르킨다.

postgresql 설정

To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

To have launchd start postgresql now and restart at login:
  brew services start postgresql
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres start

포스트그리 데이터 베이스 시작 종료

lunchy start postgres
lunchy stop postgres

포스트그리 데이터 베이스 사용법
공식 도큐먼트 링크
접속 방법

psql -U dev nomadgram -W
password = devpass -> 비밀번호 틀려도 접속 됨.

데이터베이스 생성
createdb nomadgram

데이터베이스 삭제
dropdb nomadgram

장고 서버 실행 pipenv shell - 가상환경 접속
python3 manage.py runserver

장고서버에서 데이터베이스 작업을 하기 전에 어플리케이션 작업을 해야한다. (예를들면 장바구니, 상품, 유저 등등 - 모델?)
유저는 이미 쿠키커터 덕분에 디폴트 설정을 생성 되어있다.
장고 서버는 config 설정파일의 apps를 구동 시켜 동작하는데?
apps 는 3가지가 있다.

  • DJANGO_APPS - 디폴트 설정, 유저가 설정하는게 아니라 처음 장고를 설치할때 기본적으로 설정됨.
  • THIRD_PARTY_APPS - 인터넷에서 설치하는 라이브러리 파일, 유저와 장고가 설정하는것이 아님.
  • LOCAL_APPS - 유저가 설저하는 앱. 기본적인 모델이라고 생각해도 좋을듯 (user, images, … )

app을 만들면 기본적으로 models.py , apps.py , views.py 가 생성되는데 urls.py를 추가해주자.

장고 mvc 작동 원리 사진2

18. 01. 23

  • 노마드코더 인스타 클론코딩

Python class inheritance

class Cat():
        eyes = 4
        legs = 4
        nose = 1

class BrithishCat(Cat):        // 상속
        breed = ‘brithishCat’

장고 모델 사용법 ( https://docs.djangoproject.com/en/1.11/topics/db/models/)

migrate 마이그레이션을 해야하는 이유는 기존의 데이터베이스에서 변경이 일어났을때 (생성, 수정 삭제 등) 데이터베이스 파일을 수정하기 위함이다.
예시) 새로운 column을 추가,삭제,수정 할때..

python3 manage.py migrate

장고 어드민 패널
장고 프로젝트 생성시 자동으로 관리자 페이지를 만들어 준다.
들어가는 법은 localhost:8000/admin/
관리자페이지에 로그인 하기 위해서는 superuser을 만들어 줘야한다.

python3 manage.py createsuperuser

접속하면

디폴트 설정들이 보인다. 유져는 쿠키커터에서 기본적으로 설정 해줘서
이미 만들어져 있다.

Creating the User Model
데이터 베이스 모델은 python class로 만든다.

디렉토리에 User에서 models.py를 열어 보면 user에 대한 기본적인 설정들이 이미 존재한다.

User는 abstractUser를 상속하는데 여기에는 기본적으로 name, email, FirstName, lastName 등등이 이미 존재한다.

새로운 속성은 직접 추가하면 된다.

website = models.URLField(null=True)
bio = models.TextField(null=True)
phone = models.CharField(max_length=140, null=True)
gender = models.CharField(max_length=80, choices=GENDER_CHOICES, null=True)

여기서 models는 장고가 직접 데이터 베이스로 변환시키기 위한 자료형이 설정되어있다. - model 필드 문서

속성을 추가할 때 이미 추가된 데이터에 대한 초기화값을 설정해야한다.
null 속성은 이미 추가된 속성에 대해 blank 공백을 기본값으로 제공한다.

속성들을 추가하고 저장을 하면 관리자 페이지에 접속이 안되는데 이는 데이터베이스에 변경이 생겨서 migrate를 하지 않아서다.

python manage.py makemigrations python manage.py migrate

이 후 서버를 실행하면 정상적으로 접속 된다.

Creating the Image Model

본격적으로 Image model을 만들기전 공통된 속성을 abstract class로 뽑아내자.

class TimeStampedModel(models.Model):

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

auto_now_add 속성은 데이터를 추가할때 자동으로 시간날짜가 추가된다.
auto_now 속성은 데이터를 변경하는 시간날짜가 자동으로 추가된다.

여기서 Meta 클래스안에 abstract = True 속성이 TimeStampedModel 클래스를 abstract class로 만들어준다.

가상클래스 설명

그 후 가상 클래스를 상속시켜 클래스를 만들면 된다.
User 클래스가 상속한 abstractUser 역시 이와같은 공통분모를 뽑아낸 가상 클래스이다.

class Image(TimeStampedModel):

    file = models.ImageField()
    locations = models.CharField(max_length=140)
    caption = models.TextField()



class comment(TimeStampedModel):

    message = models.TextField()

이와 같은 작업을 하고 난 후 마이그레이션을 해주면 데이터 베이스가 변경되면서 모델이 생성된다.

앞으로 할 일

  • 2018년 1년 계획 잡기()
  • 노마드코더 - 인스타그램 강의 시청
  • 회사 정리
  • 객체지향 + TDD 연습을 위한 토이프로젝트 구현 예정(로또)

Comments