Framework web Full-Stack
La page HTML est fournie par le serveur
Extension Django
Permet de simplifier la création d'une API web
Permet in fine d'alimenter une/plusieurs applications client-side
mkdir tuto
cd tuto
// Création et activation d'un environnement virtuel Python
python3 -m venv venv/
source venv/bin/activate
// Installation des dépendances
pip install django djangorestframework
django-admin startproject tuto .
django-admin startapp rest
find .
./rest/views.py
./rest/tests.py
./rest/admin.py
./rest/apps.py
./rest/models.py
./tuto/urls.py
./tuto/settings.py
./tuto/wsgi.py
./manage.py
Mettre à jour le fichier tuto/settings.py
pour lier les application django-rest-framework et rest au projet
INSTALLED_APPS = (
...
'rest_framework',
'rest.apps.RestConfig',
)
python manage migrate
python manage.py createsuperuser
--email admin@example.com
--username admin
... que l'on va placer dans le fichier rest/serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
... que l'on va placer dans le fichier rest/views.py
from django.contrib.auth.models import User
from rest.serializers import UserSerializer
from rest_framework import generics
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
... dans l'url dispatcher : tuto/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest import views
urlpatterns = [
path("users/", views.UserList.as_view()),
path("users//", views.UserDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
login : admin
mot de passe : password123