제네릭 뷰(Generic View) 살펴보기


장고의 제네릭 뷰를 살펴보고 예제를 작성해 보자.


장고는 모델(Model), 템플릿(Template), 뷰(View)로 구성된 MTV패턴 웹프레임워크이다.
이 중 뷰는 사용자 요청을 처리하고 응답을 반환하는 역할을 한다.
뷰는 함수로도, 클래스로도 구현할 수 있는데, 클래스로 구현하면 제네릭 뷰를 사용할 수 있다.

뷰를 작성하며, 제네릭 뷰의 역할 과 종류, 믹스인 뷰 등을 살펴보자!

제네릭 뷰(Generic View)

제네릭 뷰는 장고에서 기본적으로 제공하는 뷰 클래스를 의미한다. 용도에 따라 다양한 제네릭 뷰를 제공하고 있으며, 우리는 이 제네릭 뷰를 상속하고 메서드를 재정의하여 좀 더 편리하게 작업할 수 있다.
제너릭 뷰에는 용도에 따라 ListView, DetailView, FormView, TemplateView 등이 있는데, 전부 View 클래스를 상속받고 있다. 그렇기 때문에 View 클래스 메서드를 이해하면, 다른 제너릭 뷰들의 공통 메서드도 이해할 수 있을 것이다.

View

앞서 언급했듯이, 다른 제너릭 뷰가 상속받는 기본 제너릭 뷰이다. 메서드는 다음과 같다.

1. setup(request, args, *kwargs)

dispatch()전에 초기화를 수행한다. 이 메서드를 재정의하는 경우 super()를 호출해야 한다. 아래는 View에 정의된 setup() 코드이다.

1
2
3
4
5
def setup(self, request, *args, **kwargs):
"""Initialize attributes shared by all view methods."""
self.request = request
self.args = args
self.kwargs = kwargs

2. dispatch(request, args, *kwargs)

요청을 받고 HTTP 응답을 반환하는 메서드이다. GET 요청은 get()으로, POST 요청은 post() 메서드로 호출한다.

1
2
3
4
5
6
7
8
9
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)

3. http_method_not_allowed(request, args, *kwargs)

뷰가 지원하지 않는 HTTP 메서드를 호출한 경우, http_method_not_allowed() 메서드가 대신 호출된다.

1
2
3
4
5
6
def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return HttpResponseNotAllowed(self._allowed_methods())

4. options(request, args, *kwargs)

HTTP OPTIONS 요청에 대한 응답을 처리한다.

1
2
3
4
5
6
def options(self, request, *args, **kwargs):
"""Handle responding to requests for the OPTIONS HTTP verb."""
response = HttpResponse()
response['Allow'] = ', '.join(self._allowed_methods())
response['Content-Length'] = '0'
return response

기본 View 메서드를 살펴 보았으니, 다른 제너릭 뷰들을 살펴보자.

Comments