博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django之restframework
阅读量:6280 次
发布时间:2019-06-22

本文共 8999 字,大约阅读时间需要 29 分钟。

 

启动流程:引入rest_framework APP

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

 

一、序列化

  (1)Serializers

from rest_framework import serializersclass 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 tempclass 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.titleclass 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.titleclass 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 ModelSerializerfrom rest_framework import serializersfrom api import modelsclass 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 mixinsfrom rest_framework import genericsclass 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
\d+)/$', views.AuthorModelView.as_view({
"get":"list","post":"create"})),re_path(r'author/(?P
\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 BaseAuthenticationfrom rest_framework import exceptionsclass 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        if user_type==3:            return True # 通过权限认证        else:            return Falseclass 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 JSONRendererfrom 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
\w+)/', include('api.urls')), ] api/urls.py urlpatterns = [ url(r'^course/$', course.CourseView.as_view()), ]

  (3)获取

request.version

 

转载于:https://www.cnblogs.com/yinwenjie/p/10508771.html

你可能感兴趣的文章
Java NIO框架Netty教程(三) 字符串消息收发(转)
查看>>
Ucenter 会员同步登录通讯原理
查看>>
php--------获取当前时间、时间戳
查看>>
Spring MVC中文文档翻译发布
查看>>
docker centos环境部署tomcat
查看>>
JavaScript 基础(九): 条件 语句
查看>>
Linux系统固定IP配置
查看>>
配置Quartz
查看>>
Linux 线程实现机制分析
查看>>
继承自ActionBarActivity的activity的activity theme问题
查看>>
设计模式01:简单工厂模式
查看>>
项目经理笔记一
查看>>
Hibernate一对一外键双向关联
查看>>
mac pro 入手,php环境配置总结
查看>>
MyBatis-Plus | 最简单的查询操作教程(Lambda)
查看>>
rpmfusion 的国内大学 NEU 源配置
查看>>
spring jpa 配置详解
查看>>
IOE,为什么去IOE?
查看>>
java 用反射简单应用,将Object简单转换成map
查看>>
Storm中的Worker
查看>>