Framework/Django

TIL-쟝고 튜토리얼01 탐험기(Explore Django tutorial01)

청렴결백한 만능 재주꾼 2020. 4. 29. 22:21
반응형

Django

어렵다고 소문이 무성하던데 과연 어떤지 확인해보고 싶었다.

https://docs.djangoproject.com/en/3.0/intro/tutorial01/

 

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

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

docs.djangoproject.com

여기의 튜토리얼을 따라한 내용들을 적을 것이다.

일단 쟝고의 설치 유무 확인

$ python -m django --version

터미널에 입력하면 

현재 버전이 나온다.

Creating a project

$ django-admin startproject mysite

이렇게 했을 때에 여러가지가 파파박 생김.

 

directory가 두개 생기고 파이썬 파일이 6개 생겼다.

실제로 폴더에 들어가보니 만들어져 있다.

 

 

 

Outer mysite/

: 바깥 마이사이트 루트 디렉터리는 프로젝트를 담을 폴더가 된다. 이름은 바꿔도 상관없다.

 

manage.py

: 쟝고 프로젝트와 다양한 방법으로 상호작용을 할 수 있는 커맨드라인 유틸리티 입니다.

 

inner mysite/

: 프로젝트의 실제 파이썬 패키지가 될 디렉토리. 파이썬 패키지 이름이 될 디렉토리라서 뭘 넣을 때 자주 쓰게 될 것임.

 

mysite/__init__.py

: 이 디렉터리(inner mysite)가 파이썬 패키지로 간주 되어야 된다는 것을 파이썬에게 알려주는 파일.

 

mysite/settings.py

: 쟝고 프로젝트 설정 및 구성 파일. 

 

{번외:

Django settings

A Django settings file contains all the configuration of your Django installation. 

The basic - A setting file is just a Python module with module-level variables.

>>>ALLOWED_HOSTS = ['www.example.com']

>>>DEBUG = False

>>>DEFAULT_FROM_EMAIL = 'webmaster@example.com'

 

-->> If you set DEBUG to False, you also need to properly set the ALLOWED_HOSTS setting.

Because a setting file is a Python module, the following apply:

  • It doesn't allow for Python syntax errors.
  • It can assign settings dynamically using normal Python syntax. ex)MY_SETTING = [str(i) for i in range(30)]
  • It can import values form other settings files.

Designating the settings

DJANGO_SETTINGS_MODULE

When using django-admin, you can either set the environment variable once, or explicitly pass in the settings module each time you run the utility.

ex)export DJANGO_SETTINGS_MODULE=mysite.settings

django-admin runserver

 

Use the --settings command-line argument to specify the settings manually:

ex)django-admin runserver --settings=mysite.settings

 

On the server(mod_wsgi)

In your live server environment, you'll need to tell your WSGI application what setting file to use. Do that with os.environ:

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

-->> 이거는 몰라도 될 듯여.

 

Default settings

A Django settings file doesn't have to define any settings if it doesn't need to. Each setting has a sensible default value. These defaults live in the module django/conf/global_settings.py. 

-->>기본세팅을 의무적으로 할 필요는 없다. 각 세팅은 기본값을 가지고 있기 때문이다. 이러한 기본값은 django/conf/global_settings.py에 있다.

Here's the algorithm Django uses in compiling settings:

  • Load settings from global_settings.py
  • Load settings from the specified settings file, overriding the global settings as necessary.

Note that a settings file should not import from global_settings, because that's redundant.

 

Seeing which settings you've changed

The command python manage.py diffsettings displays differences between the current settings file and django's default settings.

 

Using settings in Python code

In your Django apps, use settings by importing the object django.conf.settings.

ex)

>>>from django.conf import settings

>>>if settings.DEBUG:

#Do something

 

Note that django.conf.settings isn't a module - it's an object. So importing individual settings is not possible:

from django.conf.settings imports DEBUG # this won't work

 

Altering settings at runtime

You shouldn't alter settings in your applications at runtime. For example, don't do this in a view:

>>>from django.conf import settings

>>>settings.DEBUG = True   # Do not do this!

 

 

Using settings without setting

DJANGO_SETTINGS_MODULE

 

In some cases, you might want to bypass the DJANGO_SETTINGS_MODULE environment variable. For example, if you're using the template system by itself, you likely don't want to have to set up an environment variable pointing to a settings module.

 

In these cases, you can configure Django's settings manually. Do this by calling:

Django.conf.settings.configure(default_settings,**settings)

ex)

from django.conf import settings 

settings.configure(DEBUG=True)

 

 

 


mysite/urls.py

: mysite프로젝트를 위해 URL 선언.; 장고로 돌아가는 사이트의 목차. 

 

mysite/asgi.py

: ASGI 호환 웹 서버가 프로젝트를 제공하기위한 진입 점.

 

mysite/wsgi.py

:WSGI 호환 웹 서버가 프로젝트를 제공하기위한 진입 점.

 

 

The development server

 

Let's verify your Django project works. Change into the outer mysite directory, if you haven't already, and run the following commands:

$ python manage.py runserver

치면 performing system checks...라는 글들이 나온다. 

일단 서버를 가동 시키는 명령어인 것 같다.

대략 이런 것

여기서 unapplied migrations 경고는 무시해도 된다. 그리고 어떤 유사한 생산환경에서 이 서버를 쓰지 말기를 당부한다.(번역애매..) 오직 개발을 위해 목적되어졌다.(쟝고는 비즈니스 웹서버를 만들기 위함이 아니라 비즈니스 웹 프레임워크안에 있는 것이다.)

 

이 과정들을 하고 아래의 웹페이지에 방문하면 로켓이 날아가고 있고 작동하고 있다는 화면을 보게 될 것이다.

 http://127.0.0.1:8000/

 

 Changing the port

기본적으로 runserver 명령어는 Port 8000에 있는 내부 IP에서 개발서버를 시작한다. 만약 서버의 포트를 바꾸고 싶다면 커맨드라인 인자를 집어 넣어야 한다. 만약 server가 8080포트에 시작하게 하려면 :

$python manage.py runserver 8080

을 치면 된다.

 

서버 아이피를 변경하려면 포트와 함께 전달하면 된다.

 $python manage.py runserver 0:8000

0 은 개발 서버에서 0.0.0.0 의 shortcut이다.

 

Projects vs apps

흠 이것을 갑자기 왜 짚고 넘어가는지 모르겠지만 아는 돌도 짚어보고 가야니까 짚어보자.

여기서 말하길

앱은 웹어플리케이션 인데 웹로깅 시스템이나 공공 기록 데이터베이스(?) 나 작은 설문조사 앱 등을 말함. 그니까 뭔가 큰일을 전체적으로 다루는 것이 아니라 부분부분 파트느낌. 회사로 치면 부서 느낌.

프로젝트는 그런 부서들을 담고 있는 컨테이너.  설명 끝.

 

 

Creating the Polls app

이제 나의 환경-poject-이 셋업이 되어있고, 작업을 시작할 때인데 , 각 내가 장고 파이썬 패키지로 적은 응용프로그램은 확실한 규약을 따른다. 장고는 앱의 기본 디렉터리 구조를 자동으로 생성해주는 유틸리티를 가지고 있다. 그래서 우리는 디렉터리를 만드는것에 집중하기 보다는 코딩을 적는데에 더 집중할 수 있다.

 

우리의 앱은 파이썬 path어디에나 있을 수 있다. 이제 설문조사 앱을 만들텐데 manage.py에 있는 디렉터리로 이동하자!

그리고 이 코드를 치면 된다.

$ python manage.py startapp polls

 

이거를 치는 순간 디렉터리가 생기는데 아까말한 장고가 가진 유틸리티성이다. 

그러면 왼쪽에 보이는 디렉터리를 우리는 가지게 되고 여기에서 py파일들을 수정하면서 앱을 만들어 가는 것 같다.

 

Write your first view

view는 홈페이지 첫화면을 말하는 것 같다.

Polls/views.py  - 폴스 디렉터리 안에 있는 뷰스파이를 뜻함.

ls 하고 리스트 확인한다음 cd polls해서 들어간다. 거기서 vi view.py하고 vim으로 수정해준다. 


from django.http import HttpResponse

 

def index(request):

      return HttpResponse("Hello, world. You're at the polls index.")


요런 간략한 파이썬 구문을 적어주고 esc + :wq로 저장 후 탈출한다. 

이건 장고에서 매우 간단한 뷰 구상이다. 뷰를 부르기 위해 우리는 URL에 맵핑을 해야하는데 URLconf 가 필요하다. 

여기 polls디렉토리에 urls.py를 만든다.

그러면 오른쪽 처럼 디렉토리가 구성 될 것이다.

vi urls.py

하면 새로 생길 것이고 바로 입력해준다.

polls/urls.py 에 작성 할 것은


from django.urls import path

from . import views

 

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

 


넣고 또 esc + :wq로 탈출. 이제 할일은 루트 URLconf에 polls.urls 모듈로 지정해야한다. 그래서 mysite로 이동하고 거기에 있는 urls.py를 수정하면 된다. 여기서 내가 했던 실수는 outer mysite에 urls.py를 생성하고 지우려다가 inner mysite에 있는 파일을 지워서 힘들었었다.

inner mysite 에 가서 기존에 입력되어 있는 것에 추가를 해준다.

import 에 include를 추가하고 polls/ url을 추가해준다.

 

여기서 알아 봐야 할 것은 

include() 함수와 path()함수이다.

include함수를 사용하면 다른 URLconf를 참조할 수 있다. 장고는 인클루드 안에 argument로 들어 있는 URLconf에 저장된 그 아까 입력한 (path('',views.index, name='index')이 것을 토대로 매치하고 자르고 해준다.

기본개념은 URL들을 쉽게 Plug-and-play할 수 있게 해준다는 것이다. polls.urls라고 인자를 줬기 때문에 polls가 들어간 어떤 디렉터리에 놓아져도 앱은 작동할 수 있다!! include()함수는 admin.site.urls외에는 모든 Url참조에 쓰인다.

 

 

Path() 함수:

path 함수는 요구되는 두가지의 인자(Argument)가 있다. route와 view다. 그리고 선택적 인자는 kwargs ,name 이 있다. 총 4가지의 인자를 받을 수 있는 함수이다.

 

route : 

URL 패턴이 들어있는 string이다. 요청을 처리할때, 장고는 urlpatterns의 첫번째 패턴에서 시작하여 요청 된 URL을 일치하는 패턴을 찾을 때까지 각 패턴과 비교하여 목록에서 내려간다.

 

View :

장고가 매칭패턴을 찾고 있을때, 이 인자가 불려서 Django는 일치하는 패턴을 찾으면 HttpRequest 객체를 첫 번째 인수로 사용하고 경로에서 "캡처 된"값을 키워드 인수로 사용하여 지정된 뷰 함수를 호출한다.

 

kwargs : 

키워드 인자는 딕셔너리에서 the target view에 전달된다.

 

name : 

URL 이름을 지정하면 장고내가 아니고 어디 템플릿에서든 명확하게 참조될 수 있다.

 

 

manage.py가 있는 디렉터리에서

$python manage.py runserver

를 타입하고 

http://localhost:8000/polls/

에 들어가면 다음과 같이 view설정한 것을 볼 수 있다.

 

 

 

 

반응형