Django rest_Framework (3) of Python ),

Source: Internet
Author: User

Django rest_Framework (3) of Python ),
Supplement:

Why is frontend and backend separation required:

A. Because the front-end has its own framework, the efficiency is very high.

B. Do not separate the front and back ends. If the company has both clients and apps, you can write them twice.

Benefits of the django restful framework:

We have written many components, such:

A. Authentication: there are classes and methods in the class.Authenticate/authenticate_header. Its return values include None, tuples, and exceptions. If the returned value is None, it does not matter. It is an anonymous user.

B. Permission: there are classes and methods in the class:Has_permission

C. throttling: class. The method of the class is allow_request. Here, allow_request indicates the restriction. It is restricted by IP address,

Its internal principle is: the default IP address is used by the user. This IP address may be the proxy IP address, or the proxy IP address holding the request header is put in the cache by default, the IP address of each person is p, and the list next stores its azimuth time. The current time obtained by each request is compared based on the number of times, in the comparison process, check the number of non-conforming times for comparison. If you can access the database, continue. If you cannot access the database, do not continue.

D. Version: url and hostname. Each of them has two methods: one is to help you get the version, and the other is to reverse generate the url.

E. Parser: The request body data sent by the user for operations

F. serialization: two functions: serialization and validation

I. Paging

Paging:

A. record the data id of the current access page

B. A maximum of 120 pages are displayed.

C. encrypt the page number

A. Paging Based on limit offset

Class P1 (LimitOffsetPagination): max_limit = 3 default_limit = 2 limit_query_param = 'limit' offset_query_param = 'offset' class IndexView (views. APIView): def get (self, request, * args, ** kwargs): user_list = models. userInfo. objects. all () p1 = P1 () page_user_list = p1.paginate _ queryset (queryset = user_list, request = request, view = self) ser = IndexSerializer (instance = page_user_list, region = True) return Response (ser. data) # previous and next pages not included # return p1.get _ paginated_response (ser. data) # class IndexView (views. APIView): def get (self, request, * args, ** kwargs): ret = BaseResponse () try: user_list = models. userInfo. objects. all () p1 = P1 () page_user_list = p1.paginate _ queryset (queryset = user_list, request = request, view = self) ser = IndexSerializer (instance = page_user_list, rows = True) ret. data = ser. data ret. next = p1.get _ next_link () failed t Exception as e: ret. code = 1001 ret. error = 'xxxx error' return Response (ret. _ dict __)

B. Page number-based Paging

Class P2 (PageNumberPagination): # Number of data entries displayed per page max_page_size = 5 page_size = 2 page_size_query_param = 'SIZE' # page number page_query_param = 'page'

C. Cursor-based Paging

class P3(CursorPagination):                cursor_query_param = 'cursor'                page_size = 2                ordering = 'id'
Url. py setting. py views. py url. py and the url under the views App

Ii. View

1. APIView

class IndexView(views.APIView):                    def get(self, request, *args, **kwargs):                        user_list = models.UserInfo.objects.all()                        ser = IndexSerializer(instance=user_list,many=True)                        return Response(ser.data)

2. GenericAPIview (APIView)

3. GenericViewSet (ViewSetMixin, generics. GenericAPIView)

Route modification: urlpatterns = [url (R' ^ index/$ ', views. indexView. as_view ({'get': 'LIST', 'post': 'create'}), url (R' ^ index /(? P <pk> \ d +) $ ', views. indexView. as_view ({'get': 'retrieve '}),] view modification: class IndexView (viewsets. genericViewSet): def list (self, request, * args, ** kwargs): pass # obtain list information def retrieve (self, request, * args, ** kwargs ): pass # obtain a single data record def create (self, request, * args, ** kwargs): pass custom: add POST/users/DELETE/users/1/modify PUT/users/1/patch/users/1/query GET/users/1/urlpatterns = [url (R' ^ index/$ ', Views. IndexView. as_view (), url (R' ^ index /(? P <pk> \ d +) $ ', views. indexView. as_view (),] class IndexView (views. APIView): def get (self, request, * args, ** kwargs): pk = kwargs. get ('pk') if pk: pass # get a single message else: pass # get list information def post (self, request, * args, ** kwargs ): pass def put (self, request, * args, ** kwargs): pass def patch (self, request, * args, ** kwargs): pass def delete (self, request, * args, ** kwargs): pass

4. ModelViewSet

ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet)                                                class IndexView(ModelViewSet):

 

Setting. py url. py views url. py and views

3. Routing

Category 1:

# Http: // 127.0.0.1: 8000/api/v1/auth/url (r '^ auth/$', views. authView. as_view (), # http: // 127.0.0.1: 8000/api/v1/auth. json # The url in json format (R' ^ auth \. (? P <format> [a-z0-9] +) $ ', views. authView. as_view (), # http: // 127.0.0.1: 8000/api/v1/auth/1/url (R' ^ auth /(? P <pk> \ d +)/$ ', views. authView. as_view (), # http: // 127.0.0.1: 8000/api/v1/auth/1. jsonurl (R' ^ auth /(? P <pk> \ d + )\.(? P <format> [a-z0-9] +) $ ', views. authView. as_view (), class AuthView (views. APIView): def get (self, request, * args, ** kwargs): return Response ('... ')

Category 2:

url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),url(r'^index/\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'list','post':'create'})),url(r'^index/(?P<pk>\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),url(r'^index/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),class IndexView(viewsets.ModelViewSet):queryset = models.UserInfo.objects.all()serializer_class = IndexSerializerpagination_class = P2

Category 3:

router = DefaultRouter()router.register('index',views.IndexViewSet)urlpatterns = [url(r'^', include(router.urls)),]class IndexViewSet(viewsets.ModelViewSet):queryset = models.UserInfo.objects.all()serializer_class = IndexSerializerpagination_class = P2class IndexSerializer(serializers.ModelSerializer):class Meta:model = models.UserInfofields = "__all__"


4. Renderer
When the page is displayed, data is returned.
Renderer_classes = [JSONRenderer, BrowsableAPIRenderer]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.