許可されるメソッド
CoddyのDjangoジャーニー「JSON API」セクションの一部。レッスン 8/19。
DELETE /api/tasks/を送信すると、タスクを一覧表示するコードにそのまま進み、動作したかのように200が返ります。何かを削除するよう要求したプログラムは、削除できたと思い込んでしまいます。
正しい応答は405 Method Not Allowedです。django.views.decorators.httpのデコレーターは、ビューが実行される前にこの応答を返し、ビューが受け付けるメソッドを列挙したAllowヘッダーも付けます。
@require_POST
def subscribe(request):
...
@require_http_methods(["GET", "PUT"])
def profile(request):
...require_GETとrequire_POSTは、1つのメソッドを指定する短縮形です。ビューには、たとえば@require_POSTの上にある@csrf_exemptのように、1行に1つずつ2つのデコレーターを付けられます。ビューのコードが処理するメソッドだけを正確に許可しましょう。
チャレンジ
簡単ビューが処理しないメソッドには405を返します。
task_listはGETとPOSTを受け付けます。statsとtask_detailはGETのみを受け付けます。
「実行」を押し、次に「シェル」タブで次を実行します。from django.test import Client; print(Client().delete("/api/stats/").status_code)を実行すると、405が表示されます。
自分で試してみよう
import json
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
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)
@csrf_exempt
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)
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))
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JSON APIのすべてのレッスン
自分で練習してみよう: Djangoプレイグラウンド