1.1 DjangoRestFramework基本使用
1、回顾CBV基本使用
from django.contrib import admin from django.urls import path,re_path, include urlpatterns = [ path('admin/', admin.site.urls), path('app01/', include(('app01.urls', 'app01'), namespace='app01')), # 此处include后的第一个参数用元祖传两个值,第二个值为app_name ]
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^home/',views.Home.as_view()), #as_view是指定调用view的as_view这个方法固定写法 ]
from django.shortcuts import HttpResponse from django.views import View class Home(View): '''使用CBV时必须要继承view父类''' def dispatch(self, request, *args, **kwargs): # 调用父类中的dispatch result = super(Home,self).dispatch(request, *args, **kwargs) # 使用result主动继承view父类,然后return就可以重写父类的dispath方法 return result # 在这里使用get发来请求就会调用get方法,使用post发来请求就会调用post方法 def get(self,request): print(request.method) return HttpResponse('get') def post(self,request): print(request.method,'POST') return HttpResponse('post')
2、安装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 基本使用
urlpatterns = [ url(r'^users', Users.as_view()), ]
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)
1.2 drf认证模块
1111