Restful framework【第四篇】视图组件

基本视图

写一个出版社的增删查改resful接口

路由:

url(r‘^publish/$‘, views.PublishView.as_view()),
url(r‘^publish/(?P<pk>\d+)/$‘, views.PublishDetailView.as_view()),

视图

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

class PublishView(APIView):

    def get(self, request):
        publish_list = models.Publish.objects.all()
        bs = PublishSerializers(publish_list, many=True)
        # 序列化数据

        return Response(bs.data)

    def post(self, request):
        # 添加一条数据
        print(request.data)

        bs=PublishSerializers(data=request.data)
        if bs.is_valid():
            bs.save()  # 生成记录
            return Response(bs.data)
        else:

            return Response(bs.errors)

class PublishDetailView(APIView):
    def get(self,request,pk):
        publish_obj=models.Publish.objects.filter(pk=pk).first()
        bs=PublishSerializers(publish_obj,many=False)
        return Response(bs.data)
    def put(self,request,pk):
        publish_obj = models.Publish.objects.filter(pk=pk).first()

        bs=PublishSerializers(data=request.data,instance=publish_obj)
        if bs.is_valid():
            bs.save() # update
            return Response(bs.data)
        else:
            return Response(bs.errors)
    def delete(self,request,pk):
        models.Publish.objects.filter(pk=pk).delete()

        return Response("")

mixin类和generice类编写视图

from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.generics import GenericAPIView
class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)

class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers
    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)

使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView

from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
class PublishView(ListCreateAPIView):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

class PublishDetailView(RetrieveUpdateDestroyAPIView):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

使用ModelViewSet

路由:

url(r‘^publish/$‘, views.PublishView.as_view({‘get‘:‘list‘,‘post‘:‘create‘})),
url(r‘^publish/(?P<pk>\d+)/$‘, views.PublishView.as_view({‘get‘:‘retrieve‘,‘put‘:‘update‘,‘delete‘:‘destroy‘})),

视图:

from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

原文地址:https://www.cnblogs.com/596014054-yangdongsheng/p/10228810.html

时间: 2024-10-11 11:03:35

Restful framework【第四篇】视图组件的相关文章

Restful Framework (四)

目录 一.分页 二.视图 三.路由 四.渲染器 一.分页 回到顶部 试问如果当数据量特别大的时候,你是怎么解决分页的? 方式a.记录当前访问页数的数据id 方式b.最多显示120页等 方式c.只显示上一页,下一页,不让选择页码,对页码进行加密 1.基于limit offset 做分页 from rest_framework.pagination import LimitOffsetPagination 1 urlpatterns = [ 2 url(r'^admin/', admin.site.

Restful framework【第一篇】RESTful 规范

什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行标识,客户端应用通过URL来获取资源的表征,获得这些表征致使这些应用转变状态 REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” 所有的数据,

Entity Framework 第四篇 优化SQL查询

Expression<Func<TEntity, bool>>与Func<TEntity, bool>的异同 public IList<TEntity> Search<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class { if (predicate == null) { return dbContext.Set&

Django+jenkins+python+RESTful framework(基于方法的视图)(2) 转发邮件

Send_Email.py @api_view(['POST'])def sendEmail(request): data = getRequestBody(request) print type(data) emailServer = data.get('emailServer') user = data.get('fromUser') passwd = data.get('frompasswd') recipients = data.get('toRecipients') startSend

Django+jenkins+python+RESTful framework(基于Class的视图)(4) 转发邮件

Send_Email.pyclass SendEmailViewList(BaseViewList): def __init__(self): super(SendEmailViewList, self).__init__(None) def post(self, request, format=None): data = getRequestBody(request) print type(data) emailServer = data.get('emailServer') user = d

Restful framework【第九篇】分页器

基本使用 分页 -简单分页 page_size = api_settings.PAGE_SIZE :每页显示条数 page_query_param = 'page' :查询的页码数 page_size_query_param = None :每页最大显示条数 -如果我要的数据是第一页显示10条:http://127.0.0.1:8000/books/?ccc=10&page=1 -如果我要的是第二页显示5条:http://127.0.0.1:8000/books/?ccc=5&page=2

Restful framework【第二篇】APIView

安装djangorestframework 方式一:pip3 install djangorestframework 方式二:pycharm图形化界面安装 方式三:pycharm命令行下安装(装在当前工程所用的解释器下) djangorestframework的APIView分析 as_view方法 @classmethod def as_view(cls, **initkwargs): """ Store the original class on the view fun

DRF Django REST framework 之 视图组件(四)

引言 在我们有几十上百的视图类,都有get,post等方法,在功能类似时,会导致大量的重复代码出现,显然还有很多可以优化的地方.这也就有了视图组件,它的功能非常强大,能很好的优化接口逻辑. 视图组件 使用视图组件的mixin优化接口逻辑 导入 mixins 定义序列化类 定义视图类 # 1.导入mixins from rest_framework.mixins import ( ListModelMixin, CreateModelMixin, DestroyModelMixin, Update

django rest framework 解析器组件 接口设计,视图组件 (1)

一.解析器组件 -解析器组件是用来解析用户请求数据的(application/json), content-type 将客户端发来的json数据进行解析 -必须适应APIView -request.data触发 二.序列化组件 2.1.django 自带组件serializer 2.1.1 from django.serializers import serialize2.1.2 origin_data = Book.objects.all()2.1.3 serialized_data = se

DRF之视图组件

一.知识回顾: 1.RESTful api接口规范 (1).REST最重要的一句话: url用来唯一定位资源,http请求方式用来定位用户行为. (2).设计RESTful api 2.混入类, 多继承 (1).我有一个Animal类,它包含如下方法: class Animal(object): def eat(self): print("Eat") def walk(self): print("Walk") def sleep(self): print("