Un’applicazione di test con Django e Angular (Parte 4) – Django Rest Framework

Books admin

Ora creiamo un nuovo modello per il libro. Creeremo una nuova app chiamata library e un nuovo modello chiamato Book.

Installazione di Django Rest Framework

# pip install djangorestframework django-filter django-cors-headers

Collecting djangorestframework
  Using cached djangorestframework-3.15.2-py3-none-any.whl.metadata (10 kB)
Collecting django-filter
  Using cached django_filter-25.1-py3-none-any.whl.metadata (5.1 kB)
Collecting django-cors-headers
  Using cached django_cors_headers-4.7.0-py3-none-any.whl.metadata (16 kB)
Requirement already satisfied: django>=4.2 in ./venv/lib/python3.13/site-packages (from djangorestframework) (5.1.6)
Requirement already satisfied: asgiref>=3.6 in ./venv/lib/python3.13/site-packages (from django-cors-headers) (3.8.1)
Requirement already satisfied: sqlparse>=0.3.1 in ./venv/lib/python3.13/site-packages (from django>=4.2->djangorestframework) (0.5.3)
Using cached djangorestframework-3.15.2-py3-none-any.whl (1.1 MB)
Using cached django_filter-25.1-py3-none-any.whl (94 kB)
Using cached django_cors_headers-4.7.0-py3-none-any.whl (12 kB)
Installing collected packages: djangorestframework, django-filter, django-cors-headers
Successfully installed django-cors-headers-4.7.0 django-filter-25.1 djangorestframework-3.15.2

Creiamo la nostra applicazione di test “library“

# ./manage.py startapp library

Modificare settings.py di django per abilitare library. Dobbiamo aggiornare INSTALLED_APPS aggiungendo tutte le dipendenze:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    ...
    'djangorestframework',
    'django_filters',
    'corsheaders',
    'library'
]

Per abilitare django-cors-headers dobbiamo aggiornare la sezione MIDDLEWARE aggiungendo "corsheaders.middleware.CorsMiddleware" prima di "django.middleware.common.CommonMiddleware":

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...,
]

e aggiungere le seguenti righe alla fine del file

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
  'http://localhost:4200',
)

Creare un nuovo modello per il libro

Per creare il nuovo modello dobbiamo modificare library/models.py aggiungendo la nuova classe “Book“

from django.db import models


class Book(models.Model):
    """
    Book model representing a book in the library.

    Attributes:
        title (CharField): The title of the book, with a maximum length of 100 characters.
        author (CharField): The author of the book, with a maximum length of 100 characters.
        publication_date (DateField): The publication date of the book.
        created_at (DateTimeField): The date and time when the book record was created.
        updated_at (DateTimeField): The date and time when the book record was last updated.

    Methods:
        __str__(): Returns the string representation of the book, which is its title.

    Meta:
        db_table (str): The name of the database table to use for this model ('books').
        indexes (list): A list of database indexes to create for this model, indexing the 'title' and 'author' fields.
    """

    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100, null=True)
    publication_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'books'
        indexes = [
            models.Index(fields=['title', 'author']),
        ]

Gestiremo i dati del modello Book tramite la classe BookAdmin, creiamola.

from django.contrib import admin

from django.contrib import admin
from .models import Book


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    """
    BookAdmin is a custom admin class for the Book model in the Django admin interface.

    Attributes:
        list_display (tuple): Specifies the fields to be displayed in the list view of the admin interface.
        search_fields (tuple): Specifies the fields to be searched in the admin interface.
        list_filter (tuple): Specifies the fields to be used for filtering in the admin interface.
    """
    list_display = ('title', 'author', 'publication_date',
                    'created_at', 'updated_at')
    search_fields = ('title', 'author')
    list_filter = ('author',)

Per concludere, usare i comandi ./manage.py makemigrations e ./manage.py migrate per sincronizzare lo schema del database MySQL e creare la nuova tabella books.

makemigrations

# ./manage.py makemigrations

Migrations for 'library':
  library/migrations/0001_initial.py
    + Create model Book

migrate

# ./manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, library, sessions
Running migrations:
  Applying library.0001_initial... OK

Colleghiamoci alla pagina di amministrazione di Django e gestiamo la nuova tabella.

Admin dei libri

Aggiungeremo i seguenti libri:

titleauthorpublication_date
FoundationIsaac Asimov1951-01-01
The Lord of the RingsJohn Ronald Reuel Tolkien1954-07-29
The Hitchhiker’s Guide to the GalaxyDouglas Adams1979-10-12
The HobbitJohn Ronald Reuel Tolkien1937-09-21
PinocchioCarlo Collodi1883-01-01
Crime and PunishmentFyodor Dostoevsky1866-01-01
The IdiotFyodor Dostoevsky1868-01-01
Admin dei libri

Per creare un serializer per il modello Book, devi creare un file serializers.py nella directory dell’app library. Questo file definirà la classe serializer che gestisce la conversione delle istanze del modello Book in formato JSON e viceversa.

Per prima cosa, crea un file serializers.py nella directory library, poi aggiungi il seguente codice:

from rest_framework import serializers
from .models import Book


class BookSerializer(serializers.ModelSerializer):
    """
        Serializer for the Book model.

        Serializes Book objects into JSON and deserializes JSON into Book objects.

        Attributes:
            Meta (class): A nested class that configures the serializer.
                model (Book): The Book model to serialize.
                fields (list): The fields of the Book model to include in the serialized representation.
    """
    class Meta:
        model = Book
        fields = ['id', 'title', 'author',
                  'publication_date', 'created_at', 'updated_at']

Questo codice definisce una classe BookSerializer che eredita da serializers.ModelSerializer. La classe Meta specifica il modello da serializzare (Book) e i campi da includere nell’output serializzato. Include il campo id e tutti i campi definiti nel modello Book.

Ora che hai il serializer, devi creare un ViewSet per gestire gli endpoint API del modello Book. Un ViewSet fornisce un insieme di azioni (ad es. list, create, retrieve, update, destroy) per un modello.

Crea un file views.py nella directory dell’app library (se non esiste già) e aggiungi il seguente codice:

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer


class BookViewSet(viewsets.ModelViewSet):
    """
    A viewset for viewing and editing book instances.

    This viewset provides `list`, `create`, `retrieve`, `update` and `destroy` actions for the Book model.

    Attributes:
      queryset (QuerySet): The set of Book instances to be retrieved.
      serializer_class (BookSerializer): The serializer class to be used for serializing and deserializing Book instances.
    """
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Questo codice definisce una classe BookViewSet che eredita da viewsets.ModelViewSet. Specifica il queryset (tutti gli oggetti Book ordinati per titolo) e la classe serializer (BookSerializer).

Successivamente, devi configurare i pattern URL per gli endpoint API. Crea un file urls.py nella directory dell’app library e aggiungi il seguente codice:

from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter(trailing_slash=False)
router.register(r'books', views.BookViewSet)

urlpatterns = [
  path('', include(router.urls)),
]

Questo codice usa un DefaultRouter per generare automaticamente i pattern URL per il ViewSet. Registra il BookViewSet nel router, che creerà URL come /books/ (per elencare e creare libri) e /books/{pk}/ (per leggere, aggiornare ed eliminare un libro specifico).

L’argomento trailing_slash=False nel costruttore routers.DefaultRouter() serve a rimuovere lo slash finale dai pattern URL generati dal router.

Per impostazione predefinita, il DefaultRouter di Django REST Framework genera pattern URL con uno slash finale. Ad esempio, l’URL per elencare i libri sarebbe /books/ invece di /books.

Impostando trailing_slash=False questo slash finale viene rimosso, ottenendo URL più puliti, spesso preferiti nello sviluppo web moderno. Ad esempio, l’URL per elencare i libri diventerebbe /books.

Pubblicare il servizio dei libri

Infine, includi gli URL dell’app library nel file urls.py principale del tuo progetto Django. Modifica l’urls.py principale (ad es. library/urls.py) per includere gli URL di library:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
  path('admin/', admin.site.urls),
  path('library/', include('library.urls')),
  path('api-auth/', include('rest_framework.urls'))
]

Questo include i pattern URL definiti in library/urls.py sotto il percorso /api/. Include inoltre le viste di login e logout predefinite da usare con la browsable API.

Ora puoi avviare il server di sviluppo Django e accedere agli endpoint API del modello Book. Ad esempio, puoi andare su http://localhost:8000/library/books/ per vedere l’elenco di tutti i libri in formato JSON, oppure usare la browsable API per interagire con gli endpoint.

Admin dei libri

Autenticazione API

La riga path('api-auth/', include('rest_framework.urls')) include le viste di login e logout predefinite da usare con la browsable API fornita da Django REST Framework. Questo è particolarmente utile durante lo sviluppo, perché permette di autenticarsi e testare facilmente i propri endpoint API direttamente dal browser.

Includendo rest_framework.urls ottieni automaticamente i seguenti URL:

  • login/: una vista di login che permette agli utenti di autenticarsi tramite la browsable API.
  • logout/: una vista di logout che permette agli utenti di terminare la sessione tramite la browsable API.

Queste viste usano il sistema di autenticazione di Django, quindi per poter effettuare il login dovrai avere degli utenti creati nel tuo progetto Django (ad es. tramite l’interfaccia di amministrazione).

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *