02 drf源码剖析之快速了解drf

02 drf源码剖析之快速了解drf

1. 什么是drf

  • drf是一个基于django开发的组件,本质是一个django的app
  • drf可以为我们快速开发出一个遵循restful规范的程序。

2. 安装

pip3 install djangorestframework

3. 使用

  • 注册app

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework'
    ]
    
  • 写路由

    from django.conf.urls import url
    from django.contrib import admin
    from api import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
    
        url(r'^drf/article/$', views.ArticleView.as_view()),
        url(r'^drf/article/(?P<pk>\d+)/$', views.ArticleView.as_view()),
    ]
    
    # get获取列表
    # post增加数据
    
  • 写视图

    • 根据请求方式不同做不同的操作
    class ArticleView(APIView):
        def get(self,request,*args,**kwargs):
            pk = kwargs.get('pk')
            if not pk:
                queryset = models.Article.objects.all()
                ser = serializer.ArticleSerializer(instance=queryset,many=True)
                return Response(ser.data)
            article_object = models.Article.objects.filter(id=pk).first()
            ser = serializer.ArticleSerializer(instance=article_object, many=False)
            return Response(ser.data)
    
        def post(self,request,*args,**kwargs):
            ser = serializer.ArticleSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response(ser.data)
            return Response(ser.errors)
    
        def put(self,request,*args,**kwargs):
            """全部更新"""
            pk = kwargs.get('pk')
            article_object = models.Article.objects.filter(id=pk).first()
            ser = serializer.ArticleSerializer(instance=article_object,data=request.data)
            if ser.is_valid():
                ser.save()
                return Response(ser.data)
            return Response(ser.errors)
    
        def patch(self,request,*args,**kwargs):
            """局部"""
            pk = kwargs.get('pk')
            article_object = models.Article.objects.filter(id=pk).first()
            ser = serializer.ArticleSerializer(instance=article_object, data=request.data,partial=True)
            if ser.is_valid():
                ser.save()
                return Response(ser.data)
            return Response(ser.errors)
    
        def delete(self,request,*args,**kwargs):
            """删除"""
            pk = kwargs.get('pk')
            models.Article.objects.filter(id=pk).delete()
            return Response('删除成功')
    
    
  • serializers序列化

    • serializers数据校验
    • serializers序列化
    from rest_framework import serializers
    from api import models
    class ArticleSerializer(serializers.ModelSerializer):
        category_txt = serializers.CharField(source='category.name',required=False)
        x1 = serializers.SerializerMethodField()
    
        status_txt = serializers.CharField(source='get_status_display',required=False)
    
        x2 = serializers.SerializerMethodField()
        class Meta:
            model = models.Article
            # fields = "__all__"
            fields = ['id','title','summary','content','category','category_txt','x1','status','status_txt','x2']
            # depth = 1
    
        def get_x1(self,obj):
            return obj.category.name
    
        def get_x2(self,obj):
            return obj.get_status_display()
    
    
  • 利用postman进行前端校验

    • 模拟浏览器进行发送请求

3. DRF的应用场景

  • 前后端分离项目
  • 为app写接口
  • 写移动端接口
  • 以上用drf会比较方便
posted @ 2019-11-26 20:13  LBZHK  阅读(152)  评论(0编辑  收藏  举报