שיטות מותרות
חלק מהיחידה ממשקי API של JSON במסלול ה-Django של Coddy. שיעור 8 מתוך 19.
שלח DELETE /api/tasks/, והבקשה מגיעה לקוד שמציג את המשימות: 200, כאילו היא הצליחה. תוכנית שביקשה למחוק משהו מאמינה כעת שהמחיקה בוצעה.
התשובה הכנה היא 405 Method Not Allowed. הדקורטורים שב-django.views.decorators.http מחזירים אותה לפני שה־view שלך מופעל, עם כותרת Allow שמפרטת אילו שיטות ה־view מקבל:
@require_POST
def subscribe(request):
...
@require_http_methods(["GET", "PUT"])
def profile(request):
...require_GET ו־require_POST הם הצורות המקוצרות לשיטה אחת. ל־view יכולים להיות שני דקורטורים, אחד בכל שורה, כמו @csrf_exempt מעל @require_POST. אפשר בדיוק את השיטות שהקוד של ה־view עושה בהן משהו.
אתגר
קלהחזר קוד 405 עבור שיטות שתצוגה אינה מטפלת בהן:
task_listמקבלתGETו-POST.statsו-task_detailמקבלות רקGET.
לחץ על Run, ואז בכרטיסייה Shell: הפקודה 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))
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.
כל השיעורים ביחידה ממשקי API של JSON
תרגלו בעצמכם: Django אונליין