码迷,mamicode.com
首页 > 其他好文 > 详细

rest framework-视图和路由-长期维护

时间:2020-02-11 09:37:36      阅读:42      评论:0      收藏:0      [点我收藏+]

标签:efi   elm   objects   rate   router   and   lib   end   setting   

 

通过一个小项目来研究

###############   models.py    ###############

from django.db import models


class Publish(models.Model):
    name=models.CharField(max_length=32)
    email=models.EmailField()

    def __str__(self):
        return self.name


class Author(models.Model):
    name=models.CharField(max_length=32)
    age=models.IntegerField()
    def __str__(self):
        return self.name


class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.IntegerField()
    pub_date=models.DateField()
    publish=models.ForeignKey("Publish")
    authors=models.ManyToManyField("Author")
    def __str__(self):
        return self.title


class User(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    type_choices=((1,"普通"),(2,"VIP"),(3,"SVIP"))
    user_type=models.IntegerField(choices=type_choices,default=1)


class Token(models.Model):
    user=models.OneToOneField("User")
    token=models.CharField(max_length=128)
    def __str__(self):
        return self.token

 

###############   serializers.py    ###############

from rest_framework import serializers
from api.models import *


class PublishModelSerializers(serializers.ModelSerializer):
    class Meta():
        model=Publish
        fields=‘__all__‘

class AuthorModelSerializers(serializers.ModelSerializer):
    class Meta():
        model=Author
        fields=‘__all__‘


class UserModelSerializers(serializers.ModelSerializer):
    class Meta():
        model=User
        fields=‘__all__‘

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

 

###############   views.py    ###############

from django.shortcuts import render
from api.serializer import PublishModelSerializers,AuthorModelSerializers,UserModelSerializers,BookModelSerializers
from rest_framework.views import APIView
from rest_framework.response import Response
from api import models
from api.utils import TokenAuth,SVIPPermission,VisitRateThrottle,MyPageNumberPagination


class Publisher(APIView):
    authentication_classes = [TokenAuth]
    permission_classes = [SVIPPermission]
    def get(self,request):
        publisher_all = models.Publish.objects.all()
        print(publisher_all)
        ps = PublishModelSerializers(publisher_all,many=True)
        return Response(ps.data)

    def post(self,request):
        ps = PublishModelSerializers(data=request.data)
        if ps.is_valid():
            ps.save()
            return Response(ps.data)
        else:
            return Response(ps.errors)

class PublisherDetail(APIView):
    def get(self,request,pk):
        publish = models.Publish.objects.filter(pk=pk).first()
        ps = PublishModelSerializers(publish)
        return Response(ps.data)

    def put(self,request,pk):
        publish = models.Publish.objects.filter(pk=pk).first()
        ps = PublishModelSerializers(publish,data=request.data)
        if ps.is_valid():
            ps.save()
            return Response(ps.data)
        else:
            return Response(ps.errors)

    def delete(self,request,pk):
        models.Publish.objects.filter(pk=pk).delete()
        return Response()


def get_random_str(user):
    import hashlib,time
    create_time =str(time.time())
    md5=hashlib.md5(bytes(user,encoding=‘utf8‘))
    md5.update(bytes(create_time,encoding=‘utf8‘))

    return md5.hexdigest()


class Login(APIView):
    authentication_classes = []
    def post(self,request):
        name=request.data.get(‘name‘)
        pwd = request.data.get(‘pwd‘)
        print(request.data)
        user= models.User.objects.filter(name=name,pwd=pwd).first()
        print(user)
        print(user.name)
        ret ={‘status_code‘:100,‘msg‘:None}

        if user:
            random_str = get_random_str(user.name)
            print(random_str)
            token=models.Token.objects.update_or_create(user=user,defaults={‘token‘:random_str})
            ret[‘token‘]=str(token)
        else:
            ret[‘status_code‘]=1001
            ret[‘mag‘]=‘用户名或密码错误‘

        return Response(ret)


from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets


# 第一种视图,使用mixins
class Author(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
    authentication_classes = []
    queryset = models.Author.objects.all()
    serializer_class = AuthorModelSerializers

    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)

    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)


class AuthorDetail(mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,generics.GenericAPIView):
    authentication_classes = []
    queryset = models.Author.objects.all()
    serializer_class = AuthorModelSerializers

    def get(self,request,*args,**kwargs):
        return self.retrieve(request,*args,**kwargs)

    def put(self,request,*args,**kwargs):
        return self.update(request,*args,**kwargs)

    def delete(self,request,*args,**kwargs):
        return self.destroy(request,*args,**kwargs)


# 第二种视图:使用通用的基于类的视图
class User(generics.ListCreateAPIView,generics.GenericAPIView):
    authentication_classes = []
    queryset = models.User.objects.all()
    serializer_class = UserModelSerializers


class UserDetail(generics.RetrieveUpdateDestroyAPIView,generics.GenericAPIView):
    queryset = models.User.objects.all()
    serializer_class = UserModelSerializers


# 第三种视图:把两个视图类合并成一个, 那就需要改动url了,因为url现在还是两个,

class Book(viewsets.ModelViewSet):
    # throttle_classes = [VisitRateThrottle]
    queryset = models.Book.objects.all()
    serializer_class = BookModelSerializers
    pagination_class = MyPageNumberPagination

 

###############   urls.py   ###############

from django.conf.urls import url,include
from django.contrib import admin


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

 

from django.conf.urls import url,include
from django.contrib import admin
from api import views


# 但是现在有一个问题,以后是不是只要多一个表,就需要两个url了?
# 这样有十张表就要写十次了,所以你封装了视图类了,你也需要封装一下路由,
# 怎么封装?
from rest_framework import routers
routers=routers.DefaultRouter()
routers.register("book",views.Book)
# 再有一张表,就只需要注册就可以了,
# 这样再加这样一句:routers.register("authors",views.AuthorModelView)


urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^publish/$‘,views.Publisher.as_view()),
    url(r‘^publish/(?P<pk>\d+)/$‘, views.PublisherDetail.as_view()),
    url(r‘^login/$‘, views.Login.as_view()),
    url(r‘^author/$‘, views.Author.as_view()),
    url(r‘^author/(?P<pk>\d+)/$‘, views.AuthorDetail.as_view()),
    url(r‘^user/$‘, views.User.as_view()),
    url(r‘^user/(?P<pk>\d+)/$‘, views.UserDetail.as_view()),
    url(r‘‘, include(routers.urls)),
    # url(r‘^book/$‘, views.Book.as_view({"get":"list",‘post‘:"create"})),
    # url(r‘^book/(?P<pk>\d+)/$‘, views.Book.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
]

 

###############   settings.py   ###############

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["api.utils.TokenAuth"],
    "DEFAULT_PERMISSION_CLASSES": ["api.utils.SVIPPermission"],
    ‘ALLOWED_VERSIONS‘: [‘v1‘, ‘v2‘],  # 允许的版本
    ‘VERSION_PARAM‘: ‘version‘,  # 参数
    ‘DEFAULT_VERSION‘: ‘v1‘,  # 默认版本
}

 

rest framework-视图和路由-长期维护

标签:efi   elm   objects   rate   router   and   lib   end   setting   

原文地址:https://www.cnblogs.com/andy0816/p/12293723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!