Python's Django Rest_framework

Source: Internet
Author: User
Tags auth serialization

Why to detach from front and back:

A, because the front-end it has its own framework, so that its efficiency is very high

b, do not do before and after the end of separation, if the company has both client, and the app in this case you write two times

Django RESTful Framework Benefits:

Help us write a lot of components such as:

A, authentication: there is a class, the method in the class Authenticate/authenticate_header, its return value has none, tuple, exception. If the return value is none then regardless, it is an anonymous user.

B, permissions: There are classes, methods in the class:has_permission

C, throttling: There is a class, class method: Allow_request, here allow_request to express the limit, it is limited by IP,

Its internal principle is: The default is IP, the user to use IP, this IP may proxy ip,ip or proxy IP hold the request header by default put to everyone can cache, each person's IP is P, the back of the list to save its bearing time, every request come in to get its The current time based on the number of times to compare, in the process of comparison to see the number of non-conforming time to compare, can access to continue, can not access to continue.

D, version: is the URL and hostname, they have two clocks each has two methods one is to help you get the version of the other is to help you reverse the generation of URLs

E, parser: User sent over the request body data to operate

F, Serialization: Two functions: serialization, checksum

One, pagination

Three Scenarios for paging:

A. Record the data ID of the current access page

B. Display up to 120 pages

C, the page number is encrypted

A, paging based on limit offset

Class P1 (limitoffsetpagination): Max_limit = 3 Default_limit = 2 Limit_qu Ery_param = ' limit ' Offset_query_param = ' offset ' class Inde XView (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, Many=true)                                Return Response (ser.data) # does not contain previous page and next page # return P1.get_paginated_response (Ser.data) # with previous page and next page 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,many=true) Ret.data = Ser.data                        Ret.next = P1.get_next_link () except Exception as E:ret.code= 1001 Ret.error = ' xxxx error ' return Response (ret.__dict__)

B. Page-based pagination

Class P2 (pagenumberpagination):                # Number of data bars displayed per page                max_page_size = 5                page_size = 2                page_size_query_param = ' Size '                # page                page_query_param = ' page '

C. cursor-based paging

Class P3 (cursorpagination):                cursor_query_param = ' cursor '                page_size = 2                ordering = ' id '
url.pysetting.pyviews.pyurl.py and views a URL under an app

Second, the 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 # Get list information                        Def retrieve (self, request, *args, **kwargs): Pass # Get a single piece of data                                                DEF create (Self,request, *args, **kwargs): Pass Custom: Add post/u                        sers/Delete delete/users/1/                      Change      put/users/1/Patch                             /users/1/Cha get/users/ get/users/1/Urlpattern s = [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 piece of information    Else:pass # get list Info 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.pyurl.py viewsurl.py and views a route under an app

3. Routing

First Class:

# 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 # Want to have the page display JSON format URL (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):d EF Get (Self,request,*args,**kwargs): Return Response (' ... ')

Second Category:

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

Third Category:

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 you see the page, it returns the data.
Renderer_classes = [Jsonrenderer,browsableapirenderer]

Python's Django Rest_framework

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.