React 튜토리얼

개발 2018. 4. 15. 14:40

React 튜토리얼

  1. 개발 환경

    • centos 7.0 (CentOS Linux release 7.4.1708 (Core))
  2. React 설치하기

    • npm 설치:
      [centos@centos ~]$ sudo yum install npm
      ...
      [centos@centos ~]$ npm -v
      3.10.10
      
    • create-react-app 설치
      [centos@centos ~]$ sudo npm install -g create-react-app
      ...
      [centos@centos ~]$ create-react-app --version
      1.5.2
      
      • facebook 공식 그룹 밑에 있으며 react 를 쉽게 사용할 수 있도록 지원해주는 툴 이다
  3. React App 만들기

    • 명령어: create-react-app {{ WEB_APPLICATION_NAME }}
    • 명령어 한줄로 web application 생성이 가능하다

      [centos@centos node]$ create-react-app webapp
      
      Creating a new React app in /home/centos/node/webapp.
      
      Installing packages. This might take a couple of minutes.
      Installing react, react-dom, and react-scripts...
      
      [..................] | normalizeTree: sill install loadCurrentTree
      ...
      
  4. React App 의 패키지 설명

     {{ WEB_APPLICATION_NAME }}
      ㄴ README.md
      ㄴ package.json
      ㄴ node_modules   # react 관련 모듈을 설치하면 이곳에 추가가 된다
      ㄴ public                    # index.html 이 있으며 JS, css 를 추가할때 index.html 에 선언해도 된다
      ㄴ src                          # App.js , App.css 등 react 모듈들을 정의하고 호출하는데 사용
    
    • web application 을 만들고 필요한 추가 패키기를 설치할 때에는 {{ WEB_APPLICATION_NAME 설치 경로}} 에서 npm install 을 한다
      • example:
        [centos@centos webapp]$ pwd
        /home/centos/node/webapp
        [centos@centos webapp]$ npm i react-axios
        [centos@centos webapp]$ npm install react-bootstrap-table --save
        
  5. React App 실행하기

    • node.js 를 통해 간단하게 web server 를 띄울 수 있다
    • 기본적으로 localost:3000 으로 뜨게 되며 외부에서는 접근할 수 없다

      [centos@centos webapp]$ pwd
      /home/centos/node/webapp
      [centos@centos webapp]$ npm start
      ...
      
      Compiled successfully!
      
      You can now view webapp in the browser.
      
      Local:            http://localhost:3000/
      On Your Network:  http://10.0.2.15:3000/
      
      Note that the development build is not optimized.
      To create a production build, use npm run build.
      
  6. 추가 설정사항

    • 외부 IP 를 통해 접근하도록 수정 (listen 0.0.0.0 )
      • {{ WEB_APPLICATION_PATH }}/config/webpack.config.dev.js 수정하기
        module.exports = {
        devtool: 'eval',
        entry: [
          require.resolve('webpack-dev-server/client') + '?http://0.0.0.0:8081',
          require.resolve('webpack/hot/dev-server'),
          path.join(srcPath, 'index')
        ],
        
      • {{ WEB_APPLICATION_PATH }}/scripts/start.js 수정하기
        new WebpackDevServer(compiler, {
        historyApiFallback: true,
        hot: true, // Note: only CSS is currently hot reloaded
        publicPath: config.output.publicPath,
        quiet: true,
        }).listen(3000, '0.0.0.0', function (err, result) {
        
    • 외부 통신을 위한 패키지 설치
    • table 을 만들기 위한 패키지 설치
    • chart 를 그리기 위한 패키지 설치


'개발' 카테고리의 다른 글

ELK + grafana 구축  (0) 2019.01.08
성공적인 Git 브랜치 모델  (0) 2018.10.18
vi 사용하기  (0) 2018.02.08
React 의 특징  (0) 2017.12.20
Git 입문  (0) 2017.12.17
Posted by 감각적신사
,
  1. settings.py 설정

    • mysql 데이터베이스에 사용할 app model 의 initial.py 를 생성한다
    • $ python manage.py makemigrations
      
    • mysql 데이터베이스에 app model table 을 생성한다
    • $ python manage.py migrate
      
      # Database 설정
      DATABASES = {
        # 기본으로 default 의 database 명을 받아 DB migration 을 하게 된다
        'default': {
            'ENGINE': 'django.db.backends.mysql',  # mysql db 를 사용한다
            'NAME': 'database1',                   # database 명
            'USER': 'testuser',                    # 사용자 id
            'PASSWORD': 'testpasswd',              # 사용자 password
            'HOST': 'localhost',                   # ip address
            'PORT': '3306',                        # port
        },
        # 멀티 데이터베이스를 사용하게 될 경우, setting
        'database2': {                             # database 명을 따라간다
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'database2',
            'USER': 'testuser',
            'PASSWORD': 'testpasswd',
            'HOST': 'localhost',
            'PORT': '3306',
        }
      }
      
      # 라우터를 통해 앱 별로 사용할 데이터 베이스를 선택하도록 한다
      DATABASE_ROUTERS = [
        # 프로젝트명.python패키지.python파일명.python클래스
        'django_multi_databases.MultiDatabasesRouter.Router',
      ]
      
  2. Router.py (선택사항)

    • 멀티 데이터베이스 사용시, default 를 사용하지 않을 app 에 대해서만
    • $ python manage.py migrate {app_name} --database={database_name}
      
      class Router(object):
        app_dictionary = {
            'app1' : 'default',
            'app2' : 'database2',
        }
      
        def db_for_read(self, model, **hints):
            return self.app_dictionary[model._meta.app_label];
      
        def db_for_write(self, model, **hints):
            return self.app_dictionary[model._meta.app_label];
      
        def allow_migrate(self, db, app_label, model_name=None, **hints):
            return True
      
  3. models.py

    • mysql 맵핑 object 생성

      # -*- coding: utf-8 -*-
      from __future__ import unicode_literals
      
      from django.db import models
      from django.utils import timezone
      
      class DB1Model(models.Model):
        # 기본적으로 primary 를 선언하지 않으면 id 라는 auto increments 컬럼이 생성된다
        title = models.CharField(max_length=255)
        content = models.TextField()
        likes = models.BigAutoField()
        lastModified = models.DateTimeField(default=timezone.now)
      
  4. Serializer.py

    • DB model 과 django 프레임워크 의 object 를 연결

      class DB1ModelSerializer(serializers.ModelSerializer):
      
        class Meta:
            model = DB1Model
            fields = ('id', 'title', 'content', 'likes, 'lastModified')
      
  5. views.py

    • django 프레임워크 에서 CRUD 하는 로직 생성

      class DB1ModelListCreateAPIView(generics.ListCreateAPIView):
        http_method_names = ['get', 'post']
      
        queryset = DB1Model.objects.all()
        serializer_class = serializers.DB1ModelSerializer
      
      class DB1ModelRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
        http_method_names = ['get', 'put', 'delete']
        serializer_class = serializers.DB1ModelSerializer
      
        def get_object(self):
            queryset = self.filter_queryset(self.get_queryset())
            filter_kwargs = {'id': self.kwargs['id']}
            model_instance = generics.get_object_or_404(queryset, **filter_kwargs)
            return model_instance
      
  6. urls.py

    • CRUD 동작 과 RESTful API 와 연결

      url(r'^/v1/dbmodel/$', views.DB1ModelListCreateAPIView.as_view(), name="api-dbmodel-lc"),
      url(r'^/v1/dbmodel/(?P<id>[^/]+)/$', views.DB1ModelRetrieveUpdateDestroyAPIView.as_view(), name="api-dbmodel-rud"),


Posted by 감각적신사
,

Javascript 테스트

개발/jquery 2018. 2. 14. 22:41
  1. qunit 소개

    • 링크
    • javascript 단위테스트 프레임워크 이다
    • javascript 뿐만 아니라 jQuery, jQuery UI, jQuery Mobile 에서도 사용이 가능하다
    • 장점:
      • UI 제공
      • report 제공
  2. qunit 을 이용한 test

    • 샘플을 통한 구조 이해
    •   <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width">
          <title>QUnit Example</title>
          <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.5.0.css">
        </head>
        <body>
          <div id="qunit"></div>
          <div id="qunit-fixture"></div>
          <script src="https://code.jquery.com/qunit/qunit-2.5.0.js"></script>
          <script src="https://cdn.jsdelivr.net/npm/qunit-reporter-junit@1.1.1/qunit-reporter-junit.min.js"></script>
          <script>
              <!-- TEST CASE -->
            QUnit.test( "hello test", function( assert ) {
              assert.ok( 1 == "1", "Passed!" );
            });
              <!-- TEST REPORT -->
            QUnit.jUnitReport = function(report) {
              if (typeof console !== 'undefined') {
                console.log(report.xml);
              }
            };
          </script>
        </body>
        </html>
      
      • 샘플 html 호출 결과
  3. qunit 와 phantomjs 를 활용한 js test 구성하기

     html 코드에 필요한 JS function test 만 넣어도 테스트에는 문제가 없지만
     CI 서버에 연동하여 자동배포의 한 단계로 추가하고 싶다면 ...
     step.1 test 결과를 남기고
     step.2 결과를 분석해야 한다
    
    • pre-requisites:
        # yum install fontconfig freetype freetype-devel fontconfig-devel libstdc++
      
    • 필요한 패키지 다운로드 및 압축해제
        $ wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
        $ bunzip2 phantomjs-2.1.1-linux-x86_64.tar.bz2
        $ tar xvf phantomjs-2.1.1-linux-x86_64.tar
      
    • 실행 명령어 샘플
        # runner.js 다운로드
        $ wget https://github.com/jonkemp/qunit-phantomjs-runner/blob/master/runner.js
        # test 실행
        $ /{{phantomjs 압축 해제한 폴더}}/bin/phantomjs runner.js {{테스트 할 html 파일}}
      
    • 실행 예제

        $ /{{phantomjs 압축 해제한 폴더}}/bin/phantomjs runner.js QunitTest.html
        <?xml version="1.0" encoding="UTF-8"?>
        <testsuites name="file://{{QunitTest_PATH}}/QunitTest.html" tests="2" failures="0" errors="0" time="0.008">
            <testsuite id="0" name="" hostname="localhost" tests="1" failures="0" errors="0" time="0.004" timestamp="2018-01-31T07:50:38Z">
                <testcase name="hello test" time="0.002" timestamp="2018-01-31T07:50:38Z">
                </testcase>
            </testsuite>
        </testsuites>
      
        Took 8ms to run 2 tests. 2 passed, 0 failed.
        $


'개발 > jquery' 카테고리의 다른 글

Javascript 로 파일 다운로드 구현하기  (0) 2018.01.10
table rowspan 동적 적용  (1) 2017.11.28
Posted by 감각적신사
,

vi 사용하기

개발 2018. 2. 8. 00:26

vi 사용하기

  1. .vimrc 파일 작성

     "syntax 관련 설정"
     syntax on
     syntax enable
     highlight Comment term=bold cterm=bold
    
     "indent 관련 설정"
     set autoindent
     set cindent  "set [autoindent | smartindet | cindent]"
    
     "tab"
     set ts=4 " Tab 너비
     set shiftwidth=4 " 자동 인덴트할 때 너비
    
     "기타"
     set number "set nonumber"
     set title
     set hlsearch "검색어 하이라이팅"
     set ruler "현재 커서 위치 표시"
     set showcmd "(부분적인)명령어를 상태라인에 보여줌"
     set showmatch "매치되는 괄호의 반대쪽을 보여줌"
     set history=1000 "vi 편집기록 기억갯수 .viminfo에 기록"
    
     "vi 편집간 파일선택"
     command! E Explore
    
     " 마지막 수정된 곳으로 이동"
     au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "norm g`\"" | endif
    
  2. vim 파일 사용간 유용한 명령어

    • vim 편집기 내에서 파일 탐색
      • :E
    • 자동정렬:
      • 비쥬얼 모드에서 ggvG=
      • non 비쥬얼 모드에서 gg=G
    • 문자열치환

      • :%s/foo/bar/c
        • 바꿀 때마다 바꾸어도 좋은지 물어보기에 더 안전하다. y(하나치환)/n(하나치환하지 않음)/a(전체치환) 선택가능
      • :%s/\/bar

        • 정확하게 foo에 일치될 때만 치환, fooZZZ 같은 문자열은 치환하지 않음
      • :%s/foo/bar/i

        • 대소문자 구분하지 않고 치환함


'개발' 카테고리의 다른 글

성공적인 Git 브랜치 모델  (0) 2018.10.18
React 튜토리얼  (0) 2018.04.15
React 의 특징  (0) 2017.12.20
Git 입문  (0) 2017.12.17
Docker 기초 - 1  (0) 2017.06.10
Posted by 감각적신사
,


독하게 시작하는 C 프로그래밍 - 자료형


인프런, 독하게 시작하는 C 프로그래밍

  1. 자료형
    • 정의: 일정 길이의 메모리에 저장된 정보를 해석하는 방법
    • 자료 란: 수(숫자)
      • 전자식 계산기(컴퓨터) 에 status는 두가지 밖에 없다: 0(Off) / 1 (On)
        • 1 bit (0/1 상태를 하나 가지고 있다)
        • 1 byte (4bit) 2 의 4 승 16
        • 32 bit application 이란 memory 통제범위가 4 GB 이다
        • IP 주소 255.255.255.255 > 8bit x 4 == 32 bit
    • 종류
      • 확정여부에 따라
        • 상수: 확정된 수
          • 10 이라는 정수
        • 변수: 변할 수 있는 수, 확정되지 않은 수
          • 변수에는 이름를 붙이며, 메모리(주소)를 갖게 된다
          • 주소에 가면 값(데이터)이 있다
      • 숫자의 형태에 따라
        • 정수
          • 부호가 있느냐(8bit: ASCII), 없느냐
        • 실수: 근사값처리를 하기 때문에 오차가 존재한다
          • float(32bits, 단정도, 유효형식 6자리) 실수를 표현할 일이 있으면 쓰지마라
          • double(64 bit, 배정도, 유효형식 15자리) 16자리 연산이 필요한 경우 오차가 발생한다
          • longdouble(80 bit, 특수정도, windows 에서는 double 로 인식하여 처리함)

  2. 부호체계
    • ASCII(American Standard Code Information Interchange)
      • 7 bit 부호체계 == 27 128 개의 영문,숫자, 등을 제어한다
      • A == 0x41 (8bits)
    • Unicode
      • UCS16: windows 한글은 16bits
  3. C 자료형

  4. C99 에서의 자료형
    • longlongint: 64 bits integer (표현: %lld)


'개발 > C' 카테고리의 다른 글

독하게 시작하는 C 프로그래밍 - 1  (0) 2017.06.30
Posted by 감각적신사
,

Django 프로젝트에서 batch job 돌리기

  1. django-background-tasks 모듈 활용하기

    • docs
    • 샘플 프로젝트
    • 모듈 install:
      • $ pip install django-background-tasks
        # django-compat 에 대한 의존성이 있기 때문에 관련하여 추가 업데이트가 필요할 경우도 있다
        
    • 모듈 관련 설정
      • # settings.py
          INSTALLED_APPS = (
              # ...
              'background_task', # batch job 관련 library
              # ...
          )
        
      • $ python manage.py makemigrations background_task
        $ python manage.py migrate
        
  2. 동작방식

    • django 웹과 별도의 프로세스로 동작 시키기
      • 별도의 명령어 실행
      • $ python manage.py process_tasks
        
    • django 웹안에서 동작 시키기

      • API 형태로 호출하여 실행
      • # urls.py
            urlpatterns = [
                   url(r'^v1/tasks/$', views.tasks, name='tasks'),
              ]
        
        # views.py
         @csrf_exempt
         def tasks(request):
             if request.method == 'POST':
                 message = request.POST.get('message', False)
                 return demo_task(request)
             else:
                return JsonResponse({}, status=405)
        
         @background(schedule=60)
         def demo_task(message):
            logger.debug('demo_task. message={0}'.format(message))


'개발 > python' 카테고리의 다른 글

Python multiprocess vs multithread  (0) 2018.05.24
django mysql rest api project  (0) 2018.03.11
Django 프로젝트  (0) 2017.11.29
Django 프로젝트 생성 및 App 만들기  (0) 2017.08.27
Python Django WEB project 개발하기1  (0) 2016.08.17
Posted by 감각적신사
,

Javascript 로 파일 다운로드 구현하기

  1. 목적
    • 임시로 필요한 파일에 대한 다운로드를 구현하고자 한다
    • 서버에 있는 파일을 읽어서 다운로드 시켜주는 것이 아니라 js 단에서 파일을 만들어 다운로드 시켜준다
    • 서버의 불필요한 리소스를 사용하지 않는다
  2. 구현
    • HTML
        <button id="file_download">click</button>
        <a id="download" download="" href=""></a>
      
    • Javascript
        var abc = {};
        abc['aaa'] = 'bbb';
        $("#file_download").on("click", function (e) {
            $("a#download").attr({
                "download": "download.json",
                "href": "data:application/json;charset=utf8;base64," + window.btoa(JSON.stringify(abc))
            }).get(0).click();
        });
      
  3. 구현예제


'개발 > jquery' 카테고리의 다른 글

Javascript 테스트  (0) 2018.02.14
table rowspan 동적 적용  (1) 2017.11.28
Posted by 감각적신사
,

React 의 특징

개발 2017. 12. 20. 00:35
  1. React 는 단지 View 일 뿐이다

    • python Django, Ruby, nodejs 등과 함께 사용하기 좋다
  2. javascript 기반 (+ html)

    • 다른 프레임 워크에 대한 추가 공부가 필요없다
      (angular, vue js 등 과 다르게 다른 언어를 배울 필요가 없다)
    • function / object / …
  3. composition

    • 요소(컴포넌트) 별로 나눠서 작업한다
    • 컴포넌트 란 Nav, Header, Numbers, Grid 등.. 쪼개서 작업한다 다른 곳에 붙이기 쉽다
    •  function Nav(){
           return (
             <nav>
               <ul>
                 <li></li>
                 ...
               </ul>
             </nav>
           )
       }
       fucntion Header(){
         return (
           <header>
             <img />
             <h1></h1>
             ...
           </header>
         )
       }
      
  4. Unidirectional Dataflow

    • angular 의 경우 데이터가 view, model 로 변함
    • Data 의 변경이 곧 UI 의 변경이다 (UI 을 추가로 변경시킬 필요가 없다)
    • UI 가 Data 의 변경없이 바뀔 수 없다
  5. 트랜스파일러

    • 리액트 코드를 일반 자바스크립트 코드 로 변환시켜준다
    • 웹팩 webpack.github.io : 모듈번들러

      • 브라우저가 이해할 수 있는 코드로 변경해주는 툴

      • 여러가지 장점들
        • 이미지 압출 저장, 자동으로 테스트 등 >> 인스타그램 풀스택 강의 수강 추천
    • reate react app : 페이스북에서 만들어준 웹팩 파일 손쉽게 이용하게 하기

      # Quick Overview
      npm install -g create-react-app
      
      create-react-app my-app
      cd my-app/
      npm start
      
      curl "http://localhost:3000"


'개발' 카테고리의 다른 글

React 튜토리얼  (0) 2018.04.15
vi 사용하기  (0) 2018.02.08
Git 입문  (0) 2017.12.17
Docker 기초 - 1  (0) 2017.06.10
go 언어 사용하기  (0) 2016.12.02
Posted by 감각적신사
,

Git 입문

개발 2017. 12. 17. 01:15

Git 이란


기본 참고
명령어 참고

  1. 프로젝트의 변경을 관리하는 버전관리 소프트웨어

  2. 기본 용어

    • 커맨트 라인(Command Line): 깃 명령어를 입력할 때 프롬프트로 알려진 텍스트 기반 명령어를 입력한다.
      • 저장소(Repository): 프로젝트의 디렉토리나 저장 공간.
        • Remote Repository
        • Local Repository
      • 버전관리(Version Control): 프로젝트 히스토리의 모든 시점의 “스냅샷”을 유지
      • 커밋(Commit): 커밋하면, 그 시점의 당신의 저장소의 “스냅샷”을 찍어, 프로젝트를 이전의 어떠한 상태로든 재평가하거나 복원할 수 있는 체크포인트를 가진다
    • publish: Local Repository 에서 Commit 한 스냅샷을 Remote Repository 에 반영한다
      • 브랜치(Branch): 하나의 Repository 에 대한 여러 명이 하나의 프로젝트에서 깃 없이 작업하는 것이 얼마나 혼란스러울 것인가? 일반적으로, 작업자들은 메인 프로젝트의 브랜치를 따와서(branch off), 자신이 변경하고 싶은 자신만의 버전을 만든다. 작업을 끝낸 후, 프로젝트의 메인 디렉토리인 “master”에 브랜치를 다시 “Merge”한다.
  3. 기본 동작

  4. 주요 명령어

    • git init:
      • 깃 저장소를 초기화한다
      • 이것을 입력한 후에야 추가적인 깃 명령어들을 줄 수 있다
    • git config: 처음에 깃을 설정할 때 사용
          #Git
          $ git config --global user.name "myid"
          $ git config --global user.email "myemail@mail.com"
      
    • git status:
      • 저장소 상태를 체크.
      • 현재 저장소의 어떤 브랜치에서 작업하고 있는지 등을 볼 수 있다
    • git branch:
      • 프로젝트에 새로운 브랜치를 만든다
      • dafault branch 기준으로 새브랜치를 생성한다 (기준 브랜치 선택이 가능하다)
    • git add:
      • 이 명령이 저장소에 새 파일들을 추가하진 않는다
      • 대신, 깃의 저장소 스냅샷 에 포함된다
    • git commit:
      • 깃의 가장 중요한 명령어
      • 저장소의 스냅샷 을 생성한다
      • git commit -m “Message hear”
    • git push:
      • 로컬 컴퓨터에서 작업하고 당신의 커밋한 내용을 온라인에 적용시킨다.
      • git push [remote name] [localbranch name]: local branch의 내용을 업데이트
      • git push [server] tag [TAG]: server에 tag 전송
      • git push [server] —tags: 변경된 모든 tag 전송
      • git push [server] [L.B]:[R:B]: server 에 local branch 를 Remote branch이름으로저장
    • git checkout:
      • 체크하길 원하는 저장소로 옮겨가게 해주는 탐색 명령이다.
      • master 브랜치를 들여다 보고 싶으면, git checkout master를 사용할 수 있다.
      • git checkout [branch name]: 다른 브랜치로 전환
      • git checkout -b [branch name]: branch 생성
      • git checkout [file or folder]: git repo 기준 마지막 commit 상태로 돌림
      • git checkout [id] [file or folder]: git repo 기준 id에 해당하는 commit 상태로 돌림
      • git checkout -f: 아직 commit 되지 않은 working tree와 -index 수정정사항 모두 사라짐
    • git merge:
      • 브랜치 간 변경사항을 적용하고 싶을 때
      • git merge cats 는 “cats” 브랜치에서 만든 모든 변경사항을 master로 추가한다
  5. GitHub Desktop


'개발' 카테고리의 다른 글

vi 사용하기  (0) 2018.02.08
React 의 특징  (0) 2017.12.20
Docker 기초 - 1  (0) 2017.06.10
go 언어 사용하기  (0) 2016.12.02
swagger 사용하기  (0) 2016.11.15
Posted by 감각적신사
,

Django 프로젝트

개발/python 2017. 11. 29. 00:56

Django 앱 만들기

참고

  1. 시작하기 전에

    • 프로젝트 vs. 앱
      • 프로젝트는 다양한 앱을 포함
      • 앱은 웹 어플리케이션의 기능 (e.g., 웹 블로그시스템,공공 기록의 데이터베이스 또는 간단한 투표 앱)
    • virtualenv: 개발환경에서 독립된 개발환경을 제공해주는 프로그램

          # 패키지 설치
          $ sudo pip install virtualenv
      
          # 프로젝트 생성
          $ virtualenv venv_projat
          New python executable in /naver/venv/venv_projat/bin/python
          Installing setuptools, pip, wheel...done.
      
          # 가상환경 실행
          $ source ./venv_projat/bin/activate
      
          # 가상환경 에서 사용하는 python moduel 확인
          $ pip list
          Django (1.11.3)
          pip (9.0.1)
          pytz (2017.2)
          setuptools (36.2.5)
          wheel (0.29.0)
      
          # 가상환경 종료
          $ deactivate
      
  2. Django 의 구조

    • MVT 모델
      • 좋은 참고자료
      • 모델 Model:
        • DB 구조를 설정하는 컴포넌트, ORM 방식을 사용하여 SQL 문을 직접 사용하지 않고 파이썬 객체로 접근
        • 하나의 class 가 하나의 table 을 의미한다
      • 뷰 View: (== MVC 모델의 Controller)
        • 데이터를 입력받거나 표시하는 컴포넌트
      • 템플릿 Templates: (== MVC 모델의 View)
        • 사용자의 입력과 이벤트에 반응하여 Model 과 View 를 업데이트
        • 디자인 영역의 분리 및 재사용서을 높이기 위해 HTML 구조만 따로 모아놓은 것
        • {{변수}}, {{% 태그 %}}
    • 흐름도

  3. Django 프로젝트

    • 생성

        # django-admin.py {{실행 파라미터}} {{프로젝트명}}
        $ django-admin.py startproject djangoproject
      
    • 프로젝트 구조

        djangoproject/
            ㄴ manage.py # 초기화, 마이그레이션, 실행 등을 수행하는 파일
            ㄴ djangoproject/
                    ㄴ __init__.py
                    ㄴ settings.py # 웹사이트 설정이 있는 파일
                                - ALLOWED_HOSTS: 접근 가능 호스트 정리
                                - DATABASES: 사용할 DB 정보
                                    - ENGINE:
                                        'django.db.backends.sqlite3'
                                        'django.db.backends.postgresql_psycopg2'
                                        'django.db.backends.mysql'
                                        'django.db.backends.oracle'
                                - INSTALLED_APPS:
                                    - django.contrib.auth – 인증시스템
                                    - django.contrib.contenttypes – 컨텐츠타입 프레임워크.
                                    - django.contrib.sessions – 세션프레임워크
                                    - django.contrib.sites – 한번의 Django설치로 여러 사이트 관리를 위한 프레임워크.
                                    - django.contrib.messages – 메시징 프레임워크
                                    - django.contrib.staticfiles – 정적파일을 관리하기 위한 프레임워크.
                                    - **신규 생성할 앱을  프로젝트에 추가한다.**                                
                    ㄴ urls.py # urlresolver 가 사용하는 패턴 목록을 포함
                    ㄴ wsgi.py # wsgi 호환 서버에서 서비스를 하기 위한 진입점
      
  4. Django 앱

    • 생성
      $ python manage.py startapp django1stapp
      
  5. 실행

         $ python manage.py makemigrations
         # model 의 변화 사항을 migration 폴더에 python 파일로 저장함.
         # 위에서는 ./migrations/  폴더내에 0001_initial.py 파일이 새로 생김
         # 아직 database 에 model table 생성된것은 아님
    
         $ python manage.py migrate
         # db table 생성
    
         $ python manage.py runserver ip:port
         # django project run


Posted by 감각적신사
,