Menu
CoddyTech

POST로 생성하기

Coddy Django 여정의 JSON API 섹션에 포함된 레슨. 19개 중 5번째.

프로그램은 할 일 항목을 읽을 수 있지만 추가할 수는 없습니다. 항목을 만들려면 프로그램은 요청에 함께 전송되는 데이터인 body에 할 일 항목을 JSON으로 담아 목록의 URL로 POST를 보냅니다. 양식은 request.POST를 채우지만 JSON은 그렇지 않습니다. 원시 본문인 request.body를 읽고 json.loads로 Python 객체로 변환하세요.

하나의 URL이 두 가지 작업을 할 수 있으며, request.method에 따라 작업이 선택됩니다. 이 뷰는 전달받은 내용을 그대로 응답할 뿐입니다.

import json


def echo(request):
    if request.method == "POST":
        data = json.loads(request.body)
        return JsonResponse({"you_sent": data})
    return JsonResponse({"hint": "Send me a POST"})

무언가를 생성하는 뷰는 201 Created와 새 객체를 응답하므로, 프로그램은 객체의 id를 알 수 있습니다.

주소 표시줄에서는 GET만 전송하므로, Shell 탭에서 POST를 보내 보세요. Django의 테스트용 Client는 Python에서 사이트로 요청을 보내고, .json()은 응답을 읽습니다. Shell은 이를 Python 딕셔너리로 출력합니다. 즉, JSON의 false가 아니라 'done': False로 표시됩니다.

challenge icon

챌린지

중급

프로그램에서 작업을 생성하도록 하세요.

  1. tasks/views.py에서 import json을 추가하세요. task_list의 맨 위에서 POST 요청일 때 JSON 본문의 title과 priority를 사용해 작업을 생성하세요. 기본값은 normal입니다.
  2. task_to_dict의 결과와 상태 코드 201을 응답하세요. 아래의 GET 코드는 그대로 두세요.

아래 줄을 셸 탭에서 실행하세요. 우선순위가 normal인 Pay rent가 출력됩니다.

from django.test import Client; print(Client().post("/api/tasks/", {"title": "Pay rent"}, content_type="application/json").json())

직접 해보기

from django.http import JsonResponse
from django.shortcuts import render

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)


def task_list(request):
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    return JsonResponse(task_to_dict(task))
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

JSON API의 모든 레슨

직접 연습해 보세요: Django 플레이그라운드