Menu
CoddyTech

Modificare con PATCH

Fa parte della sezione API JSON del percorso Django di Coddy. Lezione 9 di 19.

Un programma contrassegna un'attività come completata inviando {"done": true} all'URL dell'attività, e nient'altro. Quell'URL rappresenta l'attività stessa, una risorsa, e il metodo indica cosa farne: GET la legge, PATCH ne modifica una parte. Il suo metodo affine, PUT, sostituisce l'intera risorsa.

Perciò una vista PATCH modifica solo i campi presenti nel corpo. Un valore predefinito è una trappola. In un'API di libreria:

book.title = data.get("title", "")

Un programma che invia solo {"available": false} cancella il titolo. Prima verifica se la chiave è stata inviata: "title" in data è True solo in quel caso. Imposta ogni campo presente, salva una sola volta e rispondi con l'oggetto modificato. La vista ha bisogno di @csrf_exempt e del nuovo metodo in require_http_methods, come avviene per task_list.

challenge icon

Sfida

Medio

Consenti ai programmi di modificare un’attività con PATCH /api/tasks/<id>/:

  • task_detail accetta GET e PATCH ed è @csrf_exempt.
  • PATCH imposta title e done solo se sono presenti nel corpo della richiesta, salva e risponde con l’attività.
  • Se l’attività non esiste, la risposta è comunque 404.

Premi Run, poi nella scheda Shell: from django.test import Client; print(Client().patch("/api/tasks/1/", {"done": True}, content_type="application/json").json())

Provalo tu

import json

from django.http import 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)


@require_GET
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))

Tutte le lezioni di API JSON

Esercitati da solo: Playground Django