티스토리 뷰

Python/* Django

3. View Overview

포꾼 2017. 12. 12. 13:05

View (함수)

- URLConf에 매핑된 Callable Object (호출가능한 개체)

- 파이썬에는 함수 이외에도 다양한 호출 가능한 객체가 존재한다.

- 첫번쨰 인자로 무조건 httprequest 인스턴스를 받는다. HttpRequest

- 필히 HttpResponse 인스턴스를 리턴하다.

- 크게 Function Based View(함수 기반 뷰 FBV), Class Base View(클레스 기반 뷰 CBV)로 구분 된다.


1. FBV

FBV(Function Base View) 예시

1. 직접 html 소스를 작성하여 HTML형식 response (from django.http import HttpResponse)

2. 템플릿 작성을 통한 HTML 형식 response (from django.shortcuts import render)

3. JSON 형식 response (from django.http import HttpResponse, JsonResponse)

4. 파일 다운로드 response


# FBV 1번 예시 예제 (HTML형식 response)

# myapp/views.py

from django.http import HttpResponse


def post_list1(request):  ## 첫번째 인자로 무조건 request를 받는다.

     'FBV: 직접 문자열로 HTML형식 응답하기'

     name = '공유'

     return HttpResponse('''

<h1>AskDjango</h1>

<p>{name}</p>

<p> 파이썬/장고 만세</p>'''.format(name=name)) 


# FBV 2번 예시 예제 (템플릿 작성을 통한 response)

from django.shortcuts import render

def post_list2(request):

'FBV: 템플릿을 통해 HTML형식 응답하기'

name = '공유'

response = render(request, 'myapp/post_list.html', {'name': name})  

return response

<!-- myapp/templates/myapp/post_list.html -->

<h1>AskDjango</h1>

<p>{{ name }}</p>

<p> 파이썬/장고 만세 </p> 


# FBV 3번 예시 예제 (Json Response)

# myapp/views.py

from django.http import HttpResponse, JsonResponse


def post_list3(request):

'FBV: JSON 형식 응답하기'

return JsonResponse({

      'message': '안녕, 파이썬&장고',

              'items': ['파이썬', '장고', 'Celery', 'Azure', 'AWS'],

}, json_dumps_params={'ensure_ascii': True}) 

(참고) 크롬 확장프로그램 JsonView 설치를 통해 Json응답을 보기 쉽도록 표시 해줌


# FBV 4번 예씨 예제 (파일 다운로드 Response)

import os

from django.http import HttpResponse

def excel_download(request):

'FBV: 엑셀 다운로드 응답하기'

filepath = '/other/path/excel.xls'

filename = os.path.basename(filepath)

with open(filepath, 'rb') as f:

response = HttpResponse(f, content_type='application/vnd.ms-excel')

# 필요한 응답헤더 세팅

response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)

return response



2. CBV

- django.views.generic

- 뷰 사용 패턴을 일반화 시켜놓은 뷰 모음

- .as_view()클래스 함수를 통해, FBV를 생성해주는 클래스 (함수 기반 뷰를 생성해줌)


# CBV를 FBV1 예제로 표현 

from django.http import HttpResponse

from django.views.generic import View


class PostListView1(View):

'CBV: 직접 문자열로 HTML형식 응답하기'

def get(self, request):

name = '공유'

html = self.get_template_string().format(name=name)

return HttpResponse(html)


def get_template_string(self):

return '''

<h1>AskDjango</h1>

<p>{name}</p>

<p>여러분의 파이썬&장고 페이스메이커가 되겠습니다.</p>'''

post_list1 = PostListView1.as_view()

> 가급적이면 FBV로 학습하고 CBV로 진행할것


패턴화에 대한 처리는 CBV를 진행한다.




"""본 내용은 AskDjango VOD, "장고 차근차근 시작하기" 강의내용을 참고하여 작성했습니다.(https://nomade.kr/)"""

반응형

'Python > * Django' 카테고리의 다른 글

6. Django Admin  (0) 2017.12.12
5. Migration  (0) 2017.12.12
4. Django Model과 Model Fields  (0) 2017.12.12
2. URL Conf 및 정규표현식  (1) 2017.12.11
1. Django App, URLconf, Template  (0) 2017.12.11
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함