참고-http 프로토콜의 이해 및 장고 request 객체

JungSik Heo·2025년 5월 8일

1. 클라이언트(웹브라우저) 에서 서버로 전송시(POST /login)

POST /login HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer abc123
User-Agent: Mozilla/5.0
Content-Length: 49

{
  "username": "john_doe",
  "password": "1234"
}

설명:

  • Start Line: POST /login HTTP/1.1

  • Headers:
    Content-Type: JSON 형식
    Authorization: 토큰 포함
    User-Agent: 브라우저 정보

  • Boy:
    JSON 형태의 로그인 정보

2.서버 → 클라이언트: HTTP 응답 예제 (성공)

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 85
Set-Cookie: sessionid=abc123; HttpOnly; Path=/

{
  "message": "Login successful",
  "user_id": 42,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

3.장고에서 request 객체 사용법

✅ request.GET

  • 용도: URL 쿼리 문자열에서 전달된 데이터를 가져올 때 사용합니다.
  • 요청 방식: 주로 GET 요청에 사용됩니다.
  • 형태: QueryDict 객체로 반환되며, 딕셔너리처럼 사용할 수 있습니다.

예시:

# URL: /search?query=apple
query = request.GET.get('query')  # 'apple'

✅ request.data

  • 용도: 본문(body)에 담긴 데이터를 가져올 때 사용합니다.
  • 요청 방식: 주로 POST, PUT, PATCH 등에서 사용됩니다.
  • 형태: Django REST Framework (DRF)를 사용할 경우, JSON, form-data 등 다양한 타입을 자동으로 파싱해줍니다.

예시:

POST 요청 body: { "username": "john", "password": "1234" }
username = request.data.get('username')  

✅ 예시 코드로 요약

def my_view(request):
    method = request.method              # GET, POST 등
    path = request.path                  # /articles/1/
    query = request.GET.get('q')         # 쿼리 파라미터
    body = request.body                  # raw body (bytes)
    host = request.get_host()            # example.com
    full_url = request.build_absolute_uri()
    is_https = request.is_secure()
    user = request.user                  # 인증된 사용자 객체
    headers = request.headers            # 헤더 dict
profile
쿵스보이(얼짱뮤지션)

0개의 댓글