每个资源对应一个类
本课属于 Coddy Django 学习旅程的“JSON API”单元。第 11 课,共 19 课。
task_detail 现在由一串 if request.method == ... 代码块组成,还需要维护一个与它们保持同步的方法列表。Django 的基类 View 位于你使用的所有通用视图之下,负责处理这些记录工作。
为这个类的每种 HTTP 方法各定义一个方法,名称使用小写。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 上,这是每个请求都会经过的方法。
挑战
中等将 task_detail 改为一个类。
- 在
tasks/views.py中,从django.views导入View,并从django.utils.decorators导入method_decorator。 - 用
class TaskDetail(View)替换该函数和两个装饰器。它的get、patch和delete方法接收(self, request, pk),并分别执行原来对应分支的工作。 - 将
method_decorator(csrf_exempt)应用到dispatch,以豁免该类的 CSRF 保护。 - 在
tasks/urls.py中,将路由指向views.TaskDetail.as_view(),名称仍为task_detail。
打开 /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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
JSON API中的所有课
自己练习: Django 在线编辑器