django rest-framework 3.类 实现restful
上节提到过,REST框架分别提供了对函数和类的装饰器,之前已经都是通过函数来写视图函数的,现在来尝试使用class 类来实现视图函数
使用基于类编写API视图,允许重用常用的功能,减少代码重复。
一、REST框架基于类实现API
根据之前的函数视图重写基于类的视图,只涉及到了重构views.py
# 第三种 类视图
from django.http import Http404
from test_app import serializer
from test_app import models
from rest_framework import views # views.APIView 为类的装饰器
from rest_framework.response import Response
from rest_framework import status class Game_List(views.APIView):
def get(self, request, format=None):
games_obj = models.Game.objects.all()
games_serializer = serializer.Test_app_model_serializer(instance=games_obj, many=True)
return Response(games_serializer.data, status=status.HTTP_200_OK) def post(self, reqeust, format=None):
data = reqeust.data
game_serializer = serializer.Test_app_model_serializer(data=data)
if game_serializer.is_valid():
game_serializer.save()
return Response(game_serializer.data, status=status.HTTP_201_CREATED)
return Response(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
现在看起来和之前类似,但在不同的HTTP方式之间有更好的分离,继续编写更新实例视图
class Game_Info(views.APIView):
def get_obj(self, game_id):
try:
return models.Game.objects.get(id=game_id)
except models.Game.DoesNotExist as not_exist:
raise Http404 def get(self, reqeust, game_id, format=None): # 函数视图和类函数都可以使用路由系统传递过来的未命名分组数据
game_serializer = serializer.Test_app_model_serializer(instance=self.get_obj(game_id))
return Response(game_serializer.data) def put(self, request, game_id, format=None):
game_serializer = serializer.Test_app_model_serializer(instance=self.get_obj(game_id), data=request.data)
if game_serializer.is_valid():
game_serializer.save()
return Response(game_serializer.data)
return Response(game_serializer.errors) def delete(self, request, game_id, format=None):
self.get_obj(game_id).delete()
return Response(status.HTTP_204_NO_CONTENT)
二、使用mixins类实现视图函数
下面来使用REST框架的mixins类中实现
# 第四种 mixin类视图
from test_app import serializer
from test_app import models
from rest_framework import mixins
from rest_framework import generics class Game_List(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
基类提供核心功能,而mixin类提供.list()
和.create()
操作。然后,我们将明确的绑定get
和post
方法绑定到适当的操作。到目前为止足够简单的东西
class Game_Info(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer def get(self, request, *args, **kwargs):
print(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)
同样,我们正在使用的GenericAPIView
类来提供核心功能,并混入增加提供.retrieve()
,.update()
和.destroy()
方法。
三、使用泛型类视图
# 第五种 泛型类视图
from test_app import serializer
from test_app import models
from rest_framework import generics class Game_List(generics.ListCreateAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer class Game_Info(generics.RetrieveUpdateDestroyAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer
汇总:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt # 忽略post请求时的csrf问题
from test_app import serializer
from test_app import models
from rest_framework.renderers import JSONRenderer # restful提供的序列化类
from rest_framework.parsers import JSONParser # restful提供的反序列化类 # Create your views here. # # 第一种函数视图
# @csrf_exempt
# def game_list(request):
# if request.method == 'GET':
# print(request.data)
# game = models.Game.objects.all() # 获取数据库中所有数据
# game_serializer = serializer.Test_app_model_serializer(instance=game,
# many=True) # 通过自定义的serializer实例化数据,many参数为True表示处理多条数据
# # return HttpResponse(JSONRenderer().render(game_serializer.data), status=200) # 序列化serializer实例的数据
# return JsonResponse(game_serializer.data,safe=False)
# elif request.method == 'POST':
# data = JSONParser().parse(request) # 通过JsonParser类反序列化POST过来的数据
# game_serializer = serializer.Test_app_model_serializer(data=data) # 通过反序列化后的数据创建serializer实例
# print(game_serializer)
# if game_serializer.is_valid(): # 通过is_valid()方法判断数据类型是否正确,这点和Django的From相似
# game_serializer.save() # 验证通过保存数据,这里的game_serializer是自定义serializer的create函数返回的对象,进行保存
# # return HttpResponse(JSONRenderer().render(game_serializer.data)) # 序列化数据返回前端
# return JsonResponse(game_serializer.data,safe=False)
# else: # 验证不通过,输出对应的报错信息
# print("验证不通过")
# # return HttpResponse(JSONRenderer().render(game_serializer.errors))
# print(type(game_serializer.errors))
# return JsonResponse(game_serializer.errors)
#
# # 注释同上
# @csrf_exempt
# def game_info(request, game_id):
# game_obj = models.Game.objects.get(id=game_id)
# if request.method == 'GET':
# game_serializer = serializer.Test_app_model_serializer(instance=game_obj)
# data = JSONRenderer().render(game_serializer.data)
# return HttpResponse(data)
# elif request.method == 'PUT':
# data = JSONParser().parse(request)
# game_serializer = serializer.Test_app_model_serializer(instance=game_obj, data=data)
# if game_serializer.is_valid():
# game_serializer.save()
# # return HttpResponse(JSONRenderer().render(game_serializer.data))
# return JsonResponse(game_serializer.data, status=201)
# return JsonResponse(game_serializer.errors, status=400)
# elif request.method == 'DELETE':
# game_obj.delete()
# return HttpResponse(status=204) # 第二种函数视图
# from rest_framework import status
# from rest_framework.decorators import api_view
# from rest_framework.response import Response
# from test_app import serializer
# from test_app import models
#
#
# @api_view(['GET', 'POST'])
# def game_list(request, format=None):
# print(format)
# if request.method == 'GET':
# games = models.Game.objects.all()
# games_serializer = serializer.Test_app_model_serializer(instance=games, many=True)
# return Response(games_serializer.data)
# elif request.method == 'POST':
# game_serializer = serializer.Test_app_model_serializer(data=request.data)
# if game_serializer.is_valid():
# game_serializer.save()
# return Response(game_serializer.data, status=status.HTTP_201_CREATED)
# return Response(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#
# @api_view(['GET', 'PUT', 'DELETE'])
# def game_info(request, game_id, format=None):
# try:
# game_obj = models.Game.objects.get(id=game_id)
# except models.Game.DoesNotExist as e:
# return Response(status=status.HTTP_404_NOT_FOUND)
# # return HttpResponse(e,status=status.HTTP_404_NOT_FOUND)
# if request.method == 'GET':
# game_serializer = serializer.Test_app_model_serializer(instance=game_obj)
# return Response(game_serializer.data)
# elif request.method == 'PUT':
# game_serializer = serializer.Test_app_model_serializer(instance=game_obj, data=request.data)
# if game_serializer.is_valid():
# game_serializer.save()
# return Response(game_serializer.data)
# return Response(game_serializer.errors)
# elif request.method == 'DELETE':
# game_obj.delete()
# return Response(status=status.HTTP_204_NO_CONTENT) # # 第三种 APIView类视图
# from django.http import Http404
# from test_app import serializer
# from test_app import models
# from rest_framework import views
# from rest_framework.response import Response
# from rest_framework import status
#
#
# class Game_List(views.APIView):
# def get(self, request, format=None):
# print(locals())
# games_obj = models.Game.objects.all()
# games_serializer = serializer.Test_app_model_serializer(instance=games_obj, many=True)
# return Response(games_serializer.data, status=status.HTTP_200_OK)
#
# def post(self, reqeust, format=None):
# data = reqeust.data
# game_serializer = serializer.Test_app_model_serializer(data=data)
# if game_serializer.is_valid():
# game_serializer.save()
# return Response(game_serializer.data, status=status.HTTP_201_CREATED)
# return Response(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#
# class Game_Info(views.APIView):
# def get_obj(self, game_id):
# try:
# return models.Game.objects.get(id=game_id)
# except models.Game.DoesNotExist as not_exist:
# raise Http404
#
# def get(self, reqeust, game_id,format=None):
# game_serializer = serializer.Test_app_model_serializer(instance=self.get_obj(game_id))
# return Response(game_serializer.data)
#
# def put(self, request, game_id, format=None):
# game_serializer = serializer.Test_app_model_serializer(instance=self.get_obj(game_id), data=request.data)
# if game_serializer.is_valid():
# game_serializer.save()
# return Response(game_serializer.data)
# return Response(game_serializer.errors)
#
# def delete(self, request, game_id, format=None):
# self.get_obj(game_id).delete()
# return Response(status.HTTP_204_NO_CONTENT) # # 第四种 mixin类视图
# from test_app import serializer
# from test_app import models
# from rest_framework import mixins
# from rest_framework import generics
#
#
# class Game_List(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
# queryset = models.Game.objects.all()
# serializer_class = serializer.Test_app_model_serializer
#
# 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 Game_Info(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
# queryset = models.Game.objects.all()
# serializer_class = serializer.Test_app_model_serializer
#
# def get(self, request, *args, **kwargs):
# print(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) # 第五种 泛型类视图
from test_app import serializer
from test_app import models
from rest_framework import generics class Game_List(generics.ListCreateAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer class Game_Info(generics.RetrieveUpdateDestroyAPIView):
queryset = models.Game.objects.all()
serializer_class = serializer.Test_app_model_serializer
REST视图函数的实现方法
django rest-framework 3.类 实现restful的更多相关文章
- Django:Django Rest Framework
Django Rest Framework 一. 什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称 ...
- Django Rest Framework(阿奇)
Django Rest Framework 一. 什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中 ...
- 利用 Django REST framework 编写 RESTful API
利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...
- RESTful API学习Day2 - Django REST framework
Django REST framework 参考文档: 官方文档:官方文档 中文文档:中文文档 一.是什么? 基于Django开发RESTful API的一个框架 为什么要用它? 补充: CBV的 ...
- RESTful架构&简单使用Django rest framework
RESTful架构 1 什么是REST REST全称是Representational State Transfer,中文意思是表述性状态转移. 它首次出现在2000年Roy Fielding的博士论 ...
- django rest framework restful 规范
内容回顾: . django请求生命周期 -> 执行遵循wsgi协议的模块(socket服务端) -> 中间件(路由匹配) -> 视图函数(业务处理:ORM.模板渲染) -> ...
- day71:drf:API接口&Restful API规范&Django Rest Framework&drf中的序列化和反序列化功能
目录 1.web应用模式 2.API接口 3.Restful API规范 4.序列化 5.Django Rest Framework 1.drf的简单介绍 2.drf的特点 3.如何安装drf 4.d ...
- RESTful API 和 Django REST framework
100天 cmdb最后一天 #RESTful API - 定义规范 如get就是请求题 - 面向资源编程 把网络任何东西都当作资源 #给一个url,根据方法的不同对资源做不同的操作 #返回结果和状态码 ...
- 4- vue django restful framework 打造生鲜超市 -restful api 与前端源码介绍
4- vue django restful framework 打造生鲜超市 -restful api 与前端源码介绍 天涯明月笙 关注 2018.02.20 19:23* 字数 762 阅读 135 ...
- Django rest framework (视图类详解)
官网:https://www.django-rest-framework.org/api-guide/viewsets/ 在django rest framework 视图中一共有N个类 第一类:AP ...
随机推荐
- win10 安装mingw ruby rails
原文可以参考 https://ruby-china.org/topics/17581 在window10 安装ruby rails https://rubyinstaller.org/download ...
- 一句话了解JAVA与大数据之间的关系
大数据无疑是目前IT领域的最受关注的热词之一.几乎凡事都要挂上点大数据,否则就显得你OUT了.如果再找一个可以跟大数据并驾齐驱的IT热词,JAVA无疑是跟大数据并驾齐驱的一个词语.很多人在提到大数据的 ...
- Node入门教程(4)第三章:第一个 Nodejs 程序
第一个 Nodejs 程序 本教程仅适合您已经有一定的JS编程的基础或者是后端语言开发的基础.如果您是零基础,建议您先学一下老马的前端免费视频教程 第一步:创建项目文件夹 首先创建 demos 文件夹 ...
- 一个诚实的孩纸选Python的原因
我之所以会选择python语言程序设计这门课,是因为我一开始预选选的选修课都没选上,然后在补选的时候,在别人选剩的课里面选择了python. 上了两节课之后,我发现python还挺有意思的,挺喜欢py ...
- 第1章 什么是TCP-IP
第1章 什么是TCP-IP 什么是网络 网络是计算机或类似计算机的设备之间通过常用传输介质进行通信的集合.通常情况下,传输介质是绝缘的金属导线, 它用来在计算机之间携带电脉冲,介质也可以是电话线,甚至 ...
- Python内置函数(14)——bytes
英文文档: class bytes([source[, encoding[, errors]]]) Return a new "bytes" object, which is an ...
- RESTful API 编写指南
基于一些不错的RESTful开发组件,可以快速的开发出不错的RESTful API,但如果不了解开发规范的.健壮的RESTful API的基本面,即便优秀的RESTful开发组件摆在面前,也无法很好的 ...
- RocketMQ(五):namesrv初探
匠心零度 转载请注明原创出处,谢谢! RocketMQ网络部署图 NameServer:在系统中是做命名服务,更新和发现 broker服务. Broker-Master:broker 消息主机服务器. ...
- notepad++运行Python
1.打开notepad++的菜单栏,点击run 2.输入cmd /k python "$(FULL_CURRENT_PATH)" & PAUSE & EXIT 3. ...
- Python之编码
一.Python2与Python3的区别 1.从宏观上考虑,Python2重复代码太多,错误率高,不够规范.Python崇尚的是语言简洁.优美.清晰.Python3更加规范,重复代码少: 2.Pyth ...