프로그래밍

[DRF] Response 본문

Python/Django REST Framework

[DRF] Response

시케 2023. 11. 29. 09:37
728x90
반응형

2023.11.29.수

Response

장고의 Response 클래스는 HTTP 응답을 생성하고 반환하는 데 사용되는 클래스이다

기존의 HttpResponse 클래스를 확장하고 추가적인 기능과 편의성이 제공된다

 

다양한 데이터를 받아서 적절한 형식의 HTTP 응답으로 변환하며

주로 JSON 형식의 응답을 생성하는데 유용하게 사용한다

 

Response()

from rest_framework.response import Response # Response 클래스 import
from rest_framework import status

def my_api_view(request):
    data = {"message": "Hello, World!"} # 응답할 데이터
    return Response(data, status=status.HTTP_200_OK) # Response() 생성자를 통한 응답 객체 생성

 

위의 예시코드는 Response 클래스를 import하고 Response() 생성자를 통해 응답 객체를 생성하는 코드이다

응답에 대한 데이터와 HTTP 응답의 상태코드를 함께 반환하고 있다

 

Response(data, status=None, template_name=None, headers=None, content_type=None)

Response() 생성자에 대한 매개변수이다

전부 필수는 아니다

 

data: 응답에 포함될 데이터이다. 보통 Python 딕셔너리 형태로 제공되며 응답의 내용을 정의한다(data 매개변수는 자동으로 JSON 형식으로 직렬화 됨)

 

status: HTTP 응답의 상태 코드를 나타낸다. 기본값은 200(OK)이며 원하는 HTTP 상태코드 설정 가능하다

 

template_name: 응답에 사용될 템플릿의 이름을 나타낸다. 주로 HTML 응답을 생성할 때 사용된다

 

headers: 응답에 추가할 헤더를 나타낸다. 헤더는 딕셔너리 형태로 전달된다

 

content_type: 응답의 콘텐츠 유형을 나타낸다. 기본값은 'appllication/json'이다

 

data = {"message": "Hello, World!"}
response = Response(data)

from rest_framework import status
response = Response(data, status=status.HTTP_201_CREATED)

response = Response(data, template_name='my_template.html')

headers = {'Cache-Control': 'no-cache'}
response = Response(data, headers=headers)

response = Response(data, content_type='application/xml')

 

Response() 생성자를 아무런 매개변수 없이 사용하면, 

기본적으로 빈 응답이 생성되어 HTTP 상태 코드 200(OK)과 함께 빈 JSON 응답이 반환된다

> 클라이언트에게 아무 데이터가 포함되지 않은 성공적인 응답을 전송하고자 할 때 사용

 

더보기
728x90
반응형

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

[DRF] status  (0) 2023.11.29
[DRF] APIView와 api_view  (1) 2023.11.29
[DRF] Serialize(직렬화)  (1) 2023.11.28
[DRF] 페이지네이션(Pagination)  (2) 2023.11.28
[DRF] Django REST Framework  (0) 2023.11.28
Comments