django-rest-framework(一)(前言)

CBV

cbv(class base view) 类视图

实例:

路由

urlpatterns = [
    url(r'^crawlAll/', views.CrawlAll.as_view(), name='crawlAll'),
]

视图

from django.views import View
class CrawlAll(View):
    
    def get(self, request, *args, **kwargs):
        return HttpResponse('GET')

    def post(self, request, *args, **kwargs):
        return HttpResponse('POST')

    def put(self, request, *args, **kwargs):
        return HttpResponse('PUT')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('DELETE')

原理

  • 基于反射实现
  • 流程:路由 -->view -->dispatch(反射)

在进行post请求方式时,会遇到csrf token的限制,这时候有解决方案

方案一:

from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator
from django.views import View
class CrawlAll(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(CrawlAll, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return HttpResponse('GET')

    def post(self, request, *args, **kwargs):
        return HttpResponse('POST')

    def put(self, request, *args, **kwargs):
        return HttpResponse('PUT')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('DELETE')

方案二:

from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator
from django.views import View


@method_decorator(csrf_exempt, name='dispatch')
class CrawlAll(View):
   
    def get(self, request, *args, **kwargs):
        return HttpResponse('GET')

    def post(self, request, *args, **kwargs):
        return HttpResponse('POST')

    def put(self, request, *args, **kwargs):
        return HttpResponse('PUT')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('DELETE')

django请求生命周期

请求 -->uwsgi -->视图

  • (函数)–直接执行
  • (类)–> as_view -->dispatch(反射)–>执行函数

django-rest-framework请求生命周期

请求 -->uwsgi -->视图

  • (函数)–直接执行
  • (类)–> as_view -->dispatch(反射)(封装request)–>执行函数

你可能感兴趣的:(django-rest-framework(一)(前言))