REST framework

pip install djangorestframework

master/settings.py

INSTALLED_APPS = (
    ...
    'rest_framework',
)
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10
}

Creare il nuovo file didattica/serializers.py e inserire il seguente codice:

from didattica.models import Comment
from rest_framework import serializers


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment

Aggiungere al file didattica/views.py il seguente codice:

from rest_framework import viewsets
from didattica.serializers import CommentSerializer


class CommentViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

Aggiungere al file didattica/urls.py il seguente codice prima di urlpatterns:

from rest_framework import routers
from django.conf.urls import include

router = routers.DefaultRouter()
router.register(r'api/comments', views.CommentViewSet)

e aggiungere il seguente pattern alla lista urlpatterns:

    url(r'^', include(router.urls)),

Autenticarsi come amministratore http://localhost:8000/admin e accedere all'indirizzo http://localhost:8000/api/comments

Da linea di comando, shell, possiamo testare le api con il programma curl

curl -H 'Accept: application/json; indent=4' -u admin:admin123 http://localhost:8000/api/comments/

o anche (utilizzando l'id corretto al posto di 10):

curl -i -X DELETE -H 'Accept: application/json; indent=4' -u admin:admin123 http://localhost:8000/api/comments/10/

results matching ""

    No results matching ""