[Self the Python] restframework (2)

A, mixins module

1. The need to address the problem

In  [Python self] restframework  , we realized the additions and deletions publish the book and to change search (including a single query, view operating a total of five).

But if we have many examples of the same kind of need to achieve five kinds of operations, the amount of code duplication can be very large. How to solve this problem, restframework has provided a solution for us.

2.mixins module

restframework mixins module provides us with:

from rest_framwork import mixins

mixins module provides five categories for us:

mixins.ListModelMixin   # get the full amount of data (corresponding to the GET) 
mixins.CreateModelMixin   # insert data (corresponding to the POST) 
mixins.UpdateModelMixin   # update data (corresponding to PUT) 
mixins.DestroyModelMixin   # deleting data (corresponding to the Delete) 
mixins.RetrieveModelMixin   # obtain a single data (corresponding to get)

3.authors two views corresponding classes

from rest_framework import mixins
from rest_framework import generics


class AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    pass


class AuthorDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,
                     generics.GenericAPIView):
    pass

AuthorView mainly do the whole amount acquiring and creating a data, inherited ListModelMixin and CreateModelMixin.

GenericAPIView inherited from APIView, it is the use of the foundation Mixins.

For example, in AuthorView, he inherited ListModelMixin class, she had the equivalent of a list of methods called (this method is equivalent to get list view method), inherited CreateModelMixin class, she had the equivalent of a create method ( post views equivalent method), inherited GnericAPIView equivalent APIView inherited class.

Authors urls routing entries corresponding to:

from django.contrib import admin
from django.urls import path, re_path
from demo import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^publishes/$', views.PublishView.as_view(), name="publish"),
    re_path('^publishes/(?P<pk>\d+)/$', views.PublishDetailView.as_view(), name="publishdetail"),
    re_path('^books/$', views.BookView.as_view(), name="book"),
    re_path('^books/(?P<pk>\d+)/$', views.BookDetailView.as_view(), name="bookdetail"),
    re_path('^authors/$', views.AuthorView.as_view(), name="author"),
    re_path('^authors/(?P<pk>\d+)/$', views.AuthorDetailView.as_view(), name="authordetail"),
]

4. Implement class AuthorView

from rest_framework import mixins
from rest_framework import generics
from .models import Author


# Author序列化类
class AuthorModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = "__all__"


class AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

    # 获取全部authors
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    # Insert a data 
    DEF POST (Self, Request, * args, ** kwargs):
         return . Self Create (Request, * args, ** kwargs)

5. Implement class AuthorDetailView

class AuthorDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,
                       generics.GenericAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

    # Obtain a single author records 
    DEF GET (Self, Request, * args, ** kwargs):
         return . Self Retrieve (Request, * args, ** kwargs)

    # Update a record 
    DEF PUT (Self, Request, * args, ** kwargs):
         return . Self Update (Request, * args, ** kwargs)

    # Delete a record 
    DEF the Delete (Self, Request, * args, ** kwargs):
         return . Self the destroy (Request, * args, ** kwargs)

6. Test results

Get the full amount of data:

Postman request to get access http://127.0.0.1:8000/authors/:

[
    {
        "id": 1,
        "name": "leo",
        "age": 32
    },
    {
        "id": 2,
        "name": "alex",
        "age": 35
    },
    {
        "id": 3,
        "name": "Jone",
        "age": 23
    },
    {
        "id": 4,
        "name": "Lucy",
        "age": 30
    }
]

Insert a piece of data:

Postman post request to access the data http://127.0.0.1:8000/authors/,post:

{
    "name": "李雷",
    "age": 90
}

Successful return more data, then check the full amount of data:

[
    {
        "id": 1,
        "name": "leo",
        "age": 32
    },
    {
        "id": 2,
        "name": "alex",
        "age": 35
    },
    {
        "id": 3,
        "name": "Jone",
        "age": 23
    },
    {
        "id": 4,
        "name": "Lucy",
        "age": 30
    },
    {
        "id": 5,
        "name": "李雷",
        "age": 90
    }
]

Successfully inserted data.

Get a piece of data:

Postman send a get request, http: //127.0.0.1: 8000 / authors / 4 /:

Return data:

{
    "id": 4,
    "name": "Lucy",
    "age": 30
}

Modify a data:

The author 4 id is modification of the age of 33, put request to send http://127.0.0.1:8000/authors/4/, data are as follows:

{
    "name": "Lucy",
    "age": 33
}

The successful return of the above data, the query again for the message author id 4:

{
    "id": 4,
    "name": "Lucy",
    "age": 33
}

Age modified successfully.

To delete a data:

Deleting data id 4 transmits a request to delete http://127.0.0.1:8000/authors/4/.

Return null.

View full amount of data:

[
    {
        "id": 1,
        "name": "leo",
        "age": 32
    },
    {
        "id": 2,
        "name": "alex",
        "age": 35
    },
    {
        "id": 3,
        "name": "Jone",
        "age": 23
    },
    {
        "id": 5,
        "name": "李雷",
        "age": 90
    }
]

Successfully deleted data id 4.

 

 

 

 

 

 

(>‿◠)✌

 

Guess you like

Origin www.cnblogs.com/leokale-zz/p/12234348.html