04: DjangoRestFramework use

1.1 DjangoRestFramework basic use

  1. Review the basic use of CBV

from django.contrib Import ADMIN
 from django.urls Import path, re_path, the include 

the urlpatterns = [ 
    path ( ' ADMIN / ' , admin.site.urls), 
    path ( ' app01 / ' , the include (( ' app01.urls ' , ' app01 ' ), namespace = ' app01 ' )),   # the first parameter is used here to include two ancestral element values, the second value of APP_NAME 
]
urls.py
from django.conf.urls Import URL
 from app01 Import views 

the urlpatterns = [ 
    URL (R & lt ' ^ Home / ' , views.Home.as_view ()), # as_view specified call as_view view of this method of fixing wording 
]
app01/urls.py
from django.shortcuts Import HttpResponse 

from django.views Import View
 class Home (View):
     '' ' must inherit the parent view when using the CBV ' '' 
    DEF dispatch (Self, Request, * args, ** kwargs):
         # call dispatch parent class 
        result = Super (Home, Self) .dispatch (Request, * args, ** kwargs)
         # using active result inherited parent view, and then return dispath can override the parent class 
        return result
     # here use get sent a request will call the get method, using the post to send the request will call the post method 
    DEF get (Self, request):
         Print (request.method)
         return HttpResponse('get')

    def post(self,request):
        print(request.method,'POST')
        return HttpResponse('post')
views.py

  2, installation DjangoRestFramework

pip install djangorestframework==3.9.2
pip install markdown==3.0.1                  # Markdown support for the browsable API.
pip install django-filter==2.1.0             # Filtering support

  3, DjangoRestFramework basic use

urlpatterns = [
    url(r'^users', Users.as_view()),
]
urls.py
from django.views import View
from django.http import JsonResponse
 
class Users(View):
    def get(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)
 
    def post(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200) 
views.py

 1.2 drf authentication module

 

 

 

 

 

 

 

1111

Guess you like

Origin www.cnblogs.com/xiaonq/p/10987889.html
04