局部避免crsf的方式
针对视图函数:
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def foo(request): return HttpResponse("foo")
针对CBV:
# 方式1 在类上方使用 @method_decorator(csrf_exempt,name="dispatch") class IndexView(View): # 方式2 在类的 dispatch 方法上使用 @csrf_exempt @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): print("hello world") # 执行父类的dispatch方法 res=super(IndexView,self).dispatch(request, *args, **kwargs) print("hello boy") return res
在url中配置:
from django.views.decorators.csrf import csrf_exempt urlpatterns = [ url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'), ]
rest_framework的简单示例
以books为例:
(1)创建表,数据迁移
(2)创建表序列化类BookSerializer
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=Book
fields="__all__"
(3)创建视图类:
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
(4) 设计url:
router.register(r'books', views.BookViewSet)
APIview
from rest_framework.views import APIView class APIView(View): def as_view(): view = super(APIView, cls).as_view(**initkwargs) # self.dispatch def dispatch(): # 重新封装request request = self.initialize_request(request, *args, **kwargs) self.request = request # 初始化操作 self.initial(request, *args, **kwargs) if request.method.lower() in self.http_method_names:
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] handler = getattr(self, request.method.lower(),self.http_method_not_allowed)
# handler=self.get response = handler(request, *args, **kwargs) # self.get(request, *args, **kwargs) 1 CBV : as_view dispatch 2 掌握API源码流程: as_view dispatch 3 serializers组件