Computer Science/BackEnd

장고 | 장고 공식 문서 내용 정리 #1-2 Getting started : writing your first Django app, part 1

토마토. 2022. 9. 2. 14:55

첫 번째 장고 앱 작성, 2부 | 장고 문서 | 장고 (djangoproject.com)

 

Writing your first Django app, part 2 | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

첫 장고 앱 작성하기 #1

장고 문서에서는 기본적인 설문조사 웹페이지를 만든다. 

 

프로젝트 만들기
$ django-admin startproject mysite

를 수행하여 'mysite' 프로젝트를 시작해준다. 

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

그러면 현재 디렉토리에 위와 같은 폴더가 생성된다. 

각각의 역할을 살펴보자. 

  • mysite/ : 프로젝트 이름
  • manage.py : 장고 프로젝트와 상호작용하는 유틸리티
  • mysite/__init__.py : 빈 파일
  • mysite/settings.py : 설정 파일
  • mysite/urls.py : 장고 프로젝트의 URL, index를 선언하는 곳
  • mysite/asgi.py : ASGI 호환 웹서버가 프로젝트에 진입하는 곳
  • mysite/wsgi.py : WSGI 호환 웹서버가 프로젝트에 진입하는 곳
개발 서버
$ python manage.py runserver

을 실행하여 파이썬으로 작성된 경량 웹 서버를 시작한다. 

 

$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly 
until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
September 02, 2022 - 05:37:56
Django version 3.2.6, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

 

기본 포트는 8000이지만, 만약 포트 번호를 변경하고 싶다면, 명령 인수로 전달하면 된다. 

# 8080
$ python manage.py runserver 8080
# 0.0.0.0:8000
$ python manage.py runserver 0:8000

 

설문조사 앱 만들기

프로젝트는 특정 웹 사이트에 대한 구성과 앱 모읍이다. 

프로젝트 안에 여러 앱이 포함될 수 있다. 

 

아까와 동일한 디렉토리에 poll 앱을 만들어준다. (아까는 프로젝트)

$ python manage.py startapp polls

 

다음과 같은 디렉토리가 생성되었다. 

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

 

첫번째 뷰 작성
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

django http의 httpresponse와 jsonresponse와 rest-framework의 response가 뭐가 다른 걸까..

 

가장 간단한 뷰로 첫화면 index 함수를 만들어주었다. 

이제 index 함수를 호출할 url을 매핑해주기 위해 urls.py 함수를 생성해준다. 

 

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

urlpatterns 리스트에서 path('')는 루트 URLconf를 의미한다. (localhost:8000를 호출했을 때가 이것)

 

이 urls.py는 poll 앱의 하위 내용이므로, 

메인 프로젝트의 url.py에도 이 내용을 추가해준다. 

 

mysite/url.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    # include() 함수는 다른 URLConf를 가리키도록 한다. 
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

 

include()를 만나면, url의 그 지점까지를 일치시키고, 나머지를 처리하기 위해 include 내부 함수로 보낸다.

쉽게 말하자면, 위 코드에서는 polls/ 까지 맞다면, 나머지는 polls.urls에서 처리하도록 한다는 것이다. 

 

path 함수의 네 가지 인수 : 두 개는 필수(route, view), 두 개는 선택(kwargs, name)이다. 

  • route
    • URL 패턴을 포함하는 문자열
  • view
    • 뷰 함수를 호출한다. 
  • kwargs
    • 임의의 키워드 인수
  • name
    • 이름을 지정해서 템플릿 내에서 사용