Django之restframework

时间:2022-10-07 23:34:06

启动流程:引入rest_framework APP

在restframework中,GET数据可以通过request.query_params.get(xxx)获取,post数据可以通过request.data.get(xxx)获取。

一、序列化

  (1)Serializers

from rest_framework import serializers
class PublishSerializers(serializers.Serializer):
    name = serializers.CharField(max_length=32)
    email = serializers.CharField()

publish_list = models.Publish.objects.all()
ret = PublishSerializers(publish_list,many=True)  #这里many=True用来序列化QureySet对象,默认是False,用来处理model对象
class BookSerializers(serializers.Serializer):
    title = serializers.CharField()
    price = serializers.IntegerField()
    publish = serializers.CharField(source="publish.name")  #一对多字段
    authors = serializers.SerializerMethodField()           #多对多字段
    def get_authors(self,obj):
        temp=[]
        for author in obj.authors.all():
            temp.append(author.name)
        return temp

class BookView(APIView):
    def get(self,request):

        book_list = models.Book.objects.all()
        ret = BookSerializers(book_list,many=True)

        return Response(ret.data)

    def post(self,reqeust):
        pass

  (2)ModelSerializers

    表结构:

from django.db import models

# Create your models here.

class Course(models.Model):
    """
    课程信息表
    """
    title = models.CharField(max_length=32,verbose_name="课程名")
    img = models.CharField(max_length=255,verbose_name="课程图片")     #课程图片
    level_choices = (
        (1,"初级"),
        (2,"中级"),
        (3,"高级")
    )
    level = models.IntegerField(choices=level_choices,verbose_name="难易程度")
    def __str__(self):
        return self.title

class CourseDetail(models.Model):
    """
    课程详细表
    """
    course = models.OneToOneField(to="Course",on_delete=models.CASCADE)
    slogon = models.CharField(max_length=64,verbose_name="课程标语")
    reason = models.CharField(max_length=255,verbose_name="学习理由")  #学习理由
    recommand_course = models.ManyToManyField(to="course",verbose_name="推荐课程",related_name="rc")
    def __str__(self):
        return "课程详细" + self.course.title

class Chapter(models.Model):
    """
    章节
    """
    num = models.IntegerField(verbose_name="章节")
    name = models.CharField(max_length=32,verbose_name="章节名称")
    course = models.ForeignKey(to="course",on_delete=models.CASCADE)
    def __str__(self):
        return self.num + self.name

ModelSerializers

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from api import models

class CourseSerializers(ModelSerializer):
    class Meta:
        model = models.Course
        fields = "__all__"

class CourseDetailSerializers(ModelSerializer):

  #一对一/一对多字段
    title = serializers.CharField(source='course.title')
    img = serializers.CharField(source='course.img')
    level = serializers.CharField(source='course.get_level_display')
  #多对多字段
    recommand = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()

    class Meta:
        model = models.CourseDetail
        fields = ["title","img","level","recommand","slogon","reason","chapter"]     #depth = 0/1/2  可以根据深度把关联的表的信息也提取出来

    def get_recommand(self,obj):
        queryset = obj.recommand_course.all()
        return [{"id":item.id,"title":item.title} for item in queryset]

    def get_chapter(self,obj):
        queryset = obj.course.chapter_set.all()
        return [{"id":item.id,"name":item.name} for item in queryset]

添加数据:

class BookModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = "__all__"

    publish = serializers.CharField(source="publish.name")  #一对多字段

    def create(self,validated_data):    #重写create方法
        book = models.Book.objects.create(title=validated_data["title"],price=validated_data["price"],pub_date=validated_data["pub_date"],publish_id=validated_data["publish"]["pk"])
        book.authors.add(*validated_data["authors"])
        return book

class BookView(APIView):
    def get(self,request):

        book_list = models.Book.objects.all()
        ret = BookModelSerializers(book_list,many=True)

        return Response(ret.data)

    def post(self,request):

        book_obj = BookModelSerializers(data=request.data)
        if book_obj.is_valid():
            book_obj.save()
            return Response(book_obj.data)
        else:
            return HttpResponse(book_obj.errors)

二、视图

  (1)

from rest_framework import mixins
from rest_framework import generics

class AuthorView(mixins.ListModelMixins, mixins.CreateModelMixins, generics.GenericAPIView):
    queryset = models.Author.objects.all()          #固定名称
    serializers_class = AuthorModelSerializers      #固定名称

    def get(self,reqeust,*args,**kwargs):           #查看所有数据
        return self.list(reqeust,*args,**kwargs)
    def post(self,reqeust,*args,**kwargs):          #添加数据
        return self.create(reqeust,*args,**kwargs)

class AuthorDetailView(mixins.RetrieveModelMixins,mixins.DestroyModelMixins,mixins.UpdateModelMixins,generics.GenericAPIView):
    queryset = models.Author.objects.all()
    serializers_class = AuthorModelSerializers

    def get(self,reqeust,id,*args,**kwargs):
        return self.retrieve(reqeust,id,*args,**kwargs)
    def delete(self,reqeust,id,*args,**kwargs):
        return self.destroy(reqeust,id,*args,**kwargs)
    def put(self,reqeust,id,*args,**kwargs):
        return self.update(reqeust,id,*args,**kwargs)

  (2)

re_path(r'authors/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"list","post":"create"})),
re_path(r'author/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}))
class AuthorModelView(viewsets.ModelViewSet):
    queryset = models.Author.objects.all()
    serializers_class = AuthorModelSerializers

三、登录验证

def get_random_str(user):
    import hashlib,time
    ctime=str(time.time())

    md5=hashlib.md5(bytes(user,encoding="utf8"))
    md5.update(bytes(ctime,encoding="utf8"))

    return md5.hexdigest()

class LoginView(APIView):
    def post(self,request):
        name = request.data.get("name")
        pwd = request.data.get("pwd")
        user = models.User.objects.filter(name=name,pwd=pwd).first()
        res = {"status_code":1000, "msg":None}

        if user:
            random_str = get_random_str(user.name)
            token=models.Token.objects.update_or_create(user=user,defaults={"token":random_str})
            res["token"] = random_str
        else:
            res["status_code"] = 1001
            res["msg"] = "用户名或者密码错误"

        import json
        return Response(json.dumps(res,ensure_ascii=False))

三。认证组件

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions

class TokenAuth(BaseAuthentication):
    def authenticate(self,request):
        token = request.GET.get("token")
        token_obj = models.Token.objects.filter(token=token).first()
        if token_obj:
            return token_obj.user.name,token_obj.token               //一个赋值给request.user,一个赋值给request.auth
        else:
            return exceptions.AuthenticationsFailed("验证失败")

class AuthorModelView(viewsets.ModelViewSet):
    authentications_class = [TokenAuth,]

    queryset = models.Author.objects.all()
    serializers_class = AuthorModelSerializers

全局认证:

rest_framework = {
  "DEFAULT_AUTHENTICATION_CLASSES": ["app01.views.TokenAuth"]
}

四、权限组件

class SVIPPermission(object):
    message="只有超级用户才能访问"
    def has_permission(self,request,view):
        username=request.user
        user_type=User.objects.filter(name=username).first().user_type

        :

            return True # 通过权限认证
        else:
            return False

class AuthorModelView(viewsets.ModelViewSet):

    permission_classes=[SVIPPermission,]

全局权限:

REST_FRAMEWORK = {

   "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.TokenAuth",],
     "DEFAULT_PERMISSION_CLASSES": ["app01.utils.SVIPPermission",],
}

五、频率组件

class VisitRateThrottle(object):
    def allow_request(self,request):
        # 要求访问站点的频率不能超过每分钟20次
        if 1:
            return True
        else:
            return False
class AuthorModelView(viewsets.ModelViewSet):

    throttle_class = [VisitRateThrottle,]

六、解析器

七、url控制

八、响应器

九、渲染器

  规定了页面的显示效果。

from rest_framework.renderer import JSONRenderer
from rest_framework.views import APIView    

class Show(APIView):
    renderer_classes = [JSONRenderer,]            #只返回json字符串

十、版本

  (1)在settings中配置

                REST_FRAMEWORK = {
                    ....
                    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',
                    'ALLOWED_VERSIONS':['v1','v2'], # 允许的版本
                    'VERSION_PARAM':'version', # 参数
                    'DEFAULT_VERSION':'v1', # 默认版本
                    ....
                }

  (2)设置路由

                    urlpatterns = [
                        #url(r'^admin/', admin.site.urls),
                        url(r'^api/(?P<version>\w+)/', include('api.urls')),
                    ]

                api/urls.py
                    urlpatterns = [
                        url(r'^course/$', course.CourseView.as_view()),
                    ]

  (3)获取

request.version

Django之restframework的更多相关文章

  1. Django 之 restframework 频率组件的使用

    Django 之 restframework 频率组件的使用以及源码分析 频率组件的使用 第一步,先写一个频率类,继承SimpleRateThrottle 一定要在这个类里面配置一个scop='字符串 ...

  2. 【Django】 rest-framework和RestfulAPI的设计

    [rest-framework] 这是一个基于django才能发挥作用的组件,专门用于构造API的. 说到API,之前在其他项目中我也做过一些小API,不过那些都是玩票性质,结构十分简单而且要求的设计 ...

  3. 通过django的rest-framework……(CBV)

    为什么不使用FBV,因为CBV重用性很高 先看一个例子: from django.views.generic.base import View from django.http import Http ...

  4. django使用restframework实现安全的api

    参考地址:https://github.com/tomchristie/django-rest-framework/ 一般如果在批量修改多的时候,不建议使用,一般在get请求,或者修改单条数据的时候使 ...

  5. django基于restframework的CBV封装

    一.models数据库映射 from django.db import models # Create your models here. class Book(models.Model): titl ...

  6. django使用RestFramework的Token认证

    今天实现的想法有点不正规: Django Rest framework的框架的认证,API都运行良好. 现在是要自己写一个function来实现用户的功能. 而不是用Rest 框架里的APIVIEW这 ...

  7. Django 之 restframework 版本控制的使用以及源码分析

    Django rest_framework 之 版本控制 一.何为版本控制: ​ 用于版本的控制 二.内置的版本控制类: from rest_framework.versioning import Q ...

  8. django使用restframework序列化查询集合&lpar;querryset&rpar;

    第一: pip install djangorestframework 第二: 在setting.py文件中的app添加名为: 'rest_framework', 第三:再项目的APP下面新建名为(可 ...

  9. django的RestFramework模块的源码分析

    一.APIView源码分析 查看源码的前提要知道,找函数方法必须先在自己的类中找,没有再往父类找,一层一层网上找,不能直接按ctrl点击 在我们自己定义的类中没有as_view方法的函数,所以肯定是继 ...

随机推荐

  1. Java中使用Jedis操作Redis(转载)

    整理 1.字符串 添加:set keyname value 查询:get keyname 拼接:append keyname value 删除:del keyname 添加多个: mset keyna ...

  2. &lbrack;POJ3295&rsqb;Tautology

    [POJ3295]Tautology 试题描述 WFF 'N PROOF is a logic game played with dice. Each die has six faces repres ...

  3. ubuntu的目录结构

    /:根目录,一般根目录下只存放目录,不要存放文件,/etc./bin./dev./lib./sbin应该和根目录放置在一个分区中 /bin:/usr/bin:可执行二进制文件的目录,如常用的命令ls. ...

  4. Word Frequency

    https://leetcode.com/problems/word-frequency/ Write a bash script to calculate the frequency of each ...

  5. C&num;委托的介绍&lpar;delegate、Action、Func、predicate&rpar;【转】

    转自 http://www.cnblogs.com/akwwl/p/3232679.html 委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递.事件是一种特殊的委托. 1 ...

  6. &lbrack;Everyday Mathematics&rsqb;20150102

    设 \[ a_1=3,\quad a_{n+1}=\dfrac{1}{2}(a_n^2+1)\quad(n=1,2,\cdots). \] 试求 \[ \vsm{n}\dfrac{1}{1+a_n}. ...

  7. Merge Sorted Array 解答

    Question Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array ...

  8. 我的Android进阶之旅------&gt&semi;Android拍照小例子

    今天简单的学习了一下android拍照的简单实现. 当然该程序是个小例子,非常简单,没有什么复杂的操作,但是可以学习到Android 拍照API流程. 1.在布局文件中添加一个 surfaceView ...

  9. 转:java&period;io&period;IOException&colon; Exceeeded maximum number of redirects&colon; 5 解决版本

    Jmeter运行的时候出现的重定向超过n次的问题: When trying to test a Silverlight application, I get the below error. Has ...

  10. 如何在 ajax 外拿到 ajax 的数据???和ajax的参数

    第一步:  var 变量名 = $.ajax({ url: "发送请求的地址", dataType: 'json', type: 'post', async: false }) 第 ...