Proyecto: Prioridades
Parte de la sección API JSON del Journey de Django de Coddy. Lección 15 de 19.
Es hora de añadir una función por tu cuenta. Cada tarea tiene una priority: low, normal o high. La API debería permitir que los programas soliciten una prioridad y evitar que alguien invente una cuarta.
Ya tienes todas las piezas: request.GET.get() para un filtro, un QuerySet que puedes filtrar más de una vez y el diccionario errors que responde con un 400.
Los valores permitidos están definidos en el modelo. Task.Priority es una clase TextChoices, y Task.Priority.values es la lista ["low", "normal", "high"]. Comprobar los valores contra esta lista significa que se aceptará cualquier prioridad que se añada al modelo más adelante, sin cambiar la vista.
Desafío
IntermedioAñade prioridades a la API:
/api/tasks/?priority=highmuestra solo las tareas de prioridad alta y funciona con?done=:?priority=high&done=false.- Una solicitud POST con una prioridad distinta de
low,normalohighresponde con un error 400 bajo"priority"y no guarda nada. - Si no se especifica una prioridad, se usa
normal.
Pulsa Run: la vista previa muestra la única tarea de prioridad alta.
Pruébalo tú mismo
import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.utils.decorators import method_decorator
from django.views import View
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")
def task_page(request):
return render(request, "tasks/list.html", {"tasks": Task.objects.all()})
def task_row(request, pk):
task = get_object_or_404(Task, pk=pk)
return render(request, "tasks/list.html#task-row", {"task": task})
@require_GET
def stats(request):
total = Task.objects.count()
done = Task.objects.filter(done=True).count()
data = {
"total": total,
"done": done,
"open": total - done,
}
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)
def not_found():
return JsonResponse({"error": "Task not found"}, status=404)
@method_decorator(csrf_exempt, name="dispatch")
class TaskDetail(View):
def get(self, request, pk):
task = Task.objects.filter(pk=pk).first()
if task is None:
return not_found()
return JsonResponse(task_to_dict(task))
def patch(self, request, pk):
task = Task.objects.filter(pk=pk).first()
if task is None:
return not_found()
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))
def delete(self, request, pk):
task = Task.objects.filter(pk=pk).first()
if task is None:
return not_found()
task.delete()
return HttpResponse(status=204)
Todas las lecciones de API JSON
2Lectura de solicitudes
Filtrar con una consultaCrear con POST5Proyecto: Organizar el trabajo
Proyecto: PrioridadesProyecto: Borrar las tareas completadasPractica por tu cuenta: Playground de Django