Django View & URL (2)
장고는 URLconf(URL configuration)을 사용한다. URLconf 는 URL 패턴을 views에 연결한다. 이전에 Django View 와 URL (1)에서 url을 잠깐 다룬적이 있다. 이 장에서 더 자세히 살펴볼 것이다.
View와 URL
views.py
# app/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>Hello, world</h1>")
def detail(request, question_id):
return HttpResponse("You're looking at question %s" % question_id)
def results(request, question_id):
response = "You're looking at the results %s"
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s" % question_id)urls.py
다음과 같이 view와 url을 연결할 수 있다.
http://localhost:8000/polls, http://localhost:8000/polls/1, http://localhost:8000/polls/1/results, http://localhost:8000/polls/1/vote 와 같은 url로 view에 접근할 수 있다.
다음과 같이 사용자가 웹사이트의 페이지를 요청하면 Django는 mysite.urls(project.urls) 파이썬 모듈을 불러온다. 거기서 urlpatterns 변수를 찾아 순서대로 패턴을 따라간다. 그 url에 맞는 view함수를 호출하게된다.
show_urls
현재 프로젝트에 설정되어있는 URL을 한번에 볼 수 있다. 우선 django-extensions 패키지를 설치해준다. [설치하기]
그리고 난후 settings.py에 설정해준다.
여기서 url을 확인하려면 다음과 같이 명령어를 실행하면된다.
View
각 View는 **1. 요청된 페이지의 내용이 담긴 HttpResponse 객체를 반환하거나, 2. 예외처리(Http404)**를 하도록 되어있다.
데이터 베이스 레코드 읽기
템플릿 시스템 사용
PDF 생성
XML 출력
실시간 ZIP 파일 생성
view는 다음과 같은 일을 할 수 있으며, python의 어떠한 라이브러리도 사용할 수 있다.
Database API 사용하기
Database API에 접근하고 있지만 여기서는 문제가 있다. View에서 페이지의 디자인을 하드코딩 하고 있는 점이다. 템플릿(template)을 이용해서 python코드로 부터 디자인을 분리할 수 있다.
참조
Last updated
Was this helpful?