Menu
CoddyTech

リソースごとに1つのクラス

CoddyのDjangoジャーニー「JSON API」セクションの一部。レッスン 11/19。

task_detailは、if request.method == ...ブロックの連なりと、それに合わせて更新し続けるメソッドのリストになっています。これまで使ったすべての汎用ビューの基底クラスであるDjangoのViewが、この管理を担います。

クラスには、HTTPメソッドごとに1つずつメソッドを用意し、名前は小文字にします。Viewはリクエストに対応する名前のメソッドを呼び出し、それ以外のリクエストには405を返します。関数ベースのビューと同様に、URLの値はrequestの後に渡され、ルートでは.as_view()を使います。ここでは、セッションに保存する訪問者の配色テーマをリソースとして扱います。

from django.utils.decorators import method_decorator
from django.views import View

@method_decorator(csrf_exempt, name="dispatch")
class Theme(View):
    def get(self, request):
        return JsonResponse({"theme": request.session.get("theme", "light")})

    def put(self, request):
        data = json.loads(request.body)
        request.session["theme"] = data["theme"]
        return JsonResponse({"theme": data["theme"]})

@csrf_exemptは関数で使えます。クラスでは、method_decoratorを使って、すべてのリクエストが通るメソッドであるdispatchに適用します。

challenge icon

チャレンジ

中級

task_detailをクラスに変えましょう。

  1. tasks/views.pyで、django.viewsからViewを、django.utils.decoratorsからmethod_decoratorをインポートします。
  2. 関数と2つのデコレーターをclass TaskDetail(View)に置き換えます。そのget、patch、deleteは(self, request, pk)を受け取り、それぞれ以前の分岐の処理を行います。
  3. dispatchにmethod_decorator(csrf_exempt)を付けて、クラスをCSRF検証の対象外にします。
  4. tasks/urls.pyで、引き続きtask_detailという名前を使い、views.TaskDetail.as_view()にルーティングします。

/api/tasks/1/を開くと、Buy milkがJSONとして表示されます。

自分で試してみよう

import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_http_methods

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()})


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


@csrf_exempt
@require_http_methods(["GET", "POST"])
def task_list(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "The body is not valid JSON."}, status=400)
        errors = {}
        title = data.get("title", "").strip()
        if not title:
            errors["title"] = "This field is required."
        if errors:
            return JsonResponse({"errors": errors}, status=400)
        task = Task.objects.create(
            title=title,
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    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)


@csrf_exempt
@require_http_methods(["GET", "PATCH", "DELETE"])
def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    if request.method == "DELETE":
        task.delete()
        return HttpResponse(status=204)
    if request.method == "PATCH":
        data = json.loads(request.body)
        if "title" in data:
            task.title = data["title"]
        if "done" in data:
            task.done = data["done"]
        task.save()
    return JsonResponse(task_to_dict(task))
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

JSON APIのすべてのレッスン

自分で練習してみよう: Djangoプレイグラウンド