首页 > 代码库 > Djano之写api使用django_rest_framework【海瑞博客】
Djano之写api使用django_rest_framework【海瑞博客】
使用django rest framework 可以更快速和友好的编写api,当然网上有很多教程,对于高手来说相对很简单,对于新手来说,根本搞不明白。那是你没有搞明白你自己的职责,做为后端,我们只要提供接口即可,根据提供的参数,对于返回数据。所以,我们需要友好的返回数据并有说明。
官方网站:
http://www.django-rest-framework.org/
中文教程:
Django-REST-framework教程中文版.pdf
OK 开始学习吧!
首先Model
class Disk(models.Model):
"""
"""
identify = models.CharField(max_length=64)
description = models.CharField(max_length=64, default=u‘500G*2‘)
orgid = models.CharField(max_length=24)
def __unicode__(self):
return "%s" % self.description
class Meta:
unique_together = (‘identify‘, ‘orgid‘)
urls写法
from rest_framework import routers
from django.conf.urls import url, include
# 创建路由对象
router = routers.DefaultRouter()
# 将url 注册到路由对象中
router.register(r‘assets/(?P<orgid>\d+)‘, views.AssetViewSet)
# 第一个url 就是我们正常的就可以了,后面2个必须是这种写法,一个字都不能错的
urlpatterns = [
url(r‘^assets/(?P<orgid>\d+)/upload$‘, fileviews.AssetUploadViewSet.as_view()),
url(r‘^‘, include(router.urls)),
url(r‘^api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)),
]
创建一个serializers.py
from rest_framework import serializers
from models import Disk
class DiskSerializer(serializers.ModelSerializer):
def validate(self, data):
"""
数据验证并保证数据的一致性
"""
if not data[‘identify‘] or not data[‘orgid‘]:
raise serializers.ValidationError("Must have fields: identify, orgid")
if data[‘identify‘]:
if Disk.objects.filter(identify=data[‘identify‘], orgid=data[‘orgid‘]):
raise serializers.ValidationError("Data is duplicated")
return data
def create(self, validated_data):
‘’‘新建’‘’
disk_obj = Disk.objects.create(**validated_data)
return disk_obj
def update(self, instance, validated_data):
‘‘‘更新‘‘‘
instance.identify = validated_data.get(‘identify‘, instance.identify)
instance.description = validated_data.get(‘description‘, instance.description)
instance.orgid = validated_data.get(‘orgid‘, instance.orgid)
instance.save()
return instance
class Meta:
model = Disk
fields = "__all__"
views写法
from django.shortcuts import render, get_object_or_404, get_list_or_404
from rest_framework import generics, viewsets
from rest_framework.response import Response
from rest_framework import permissions
from models import Disk
from serializers import DiskSerializer
class DiskViewSet(viewsets.ModelViewSet):
"""
硬盘的views
"""
queryset = Disk.objects.all()
serializer_class = DiskSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def list(self, request, *args, **kwargs):
‘‘‘
返回所有数据列表,get
‘‘‘
orgid = self.kwargs[‘orgid‘]
self.queryset = Disk.objects.filter(orgid=orgid)
serializer = DiskSerializer(self.queryset, many=True)
return Response({
"status": 0,
"data": serializer.data,
"msg": ""
})
def retrieve(self, request, *args, **kwargs):
‘‘‘条件查询‘‘‘
orgid = self.kwargs[‘orgid‘]
pk = self.kwargs[‘pk‘]
liaison = get_object_or_404(self.queryset, identify=pk, orgid=orgid)
serializer = DiskSerializer(liaison)
return Response({
"status": 0,
"data": serializer.data,
"msg": ""
})
def create(self, request, *args, **kwargs):
‘‘‘创建数据列表 post的时候走此方法‘‘‘
orgid = self.kwargs[‘orgid‘]
request.data.update({‘orgid‘: orgid})
if Disk.objects.filter(identify=request.data[‘identify‘], orgid=orgid).count() == 0:
serializer = DiskSerializer(data=http://www.mamicode.com/request.data)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response({
"status": 0,
"data": "",
"msg": "create Disk liaison success"
})
return Response({
"status": 1,
"data": "",
"msg": " Disk liaison existed"
})
def update(self, request, *args, **kwargs):
‘‘‘更新数据,put‘‘‘
partial = kwargs.pop(‘partial‘, False)
orgid = self.kwargs[‘orgid‘]
pk = self.kwargs[‘pk‘]
instance = get_object_or_404(self.queryset, identify=pk, orgid=orgid)
serializer = self.get_serializer(instance, request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response({
"status": 0,
"data": serializer.data,
"msg": ""
})
def destroy(self, request, *args, **kwargs):
‘‘‘数据‘‘‘
partial = kwargs.pop(‘partial‘, False)
orgid = self.kwargs[‘orgid‘]
pk = self.kwargs[‘pk‘]
instance = get_object_or_404(self.queryset, identify=pk, orgid=orgid)
self.perform_destroy(instance)
return Response({
"status": 0,
"data": "",
"msg": "delete Memory liaison success"
})
我们来说说我们关心的问题
第一:我们get带的参数去哪去取?
在get请求都是获取数据,那我们传的数据都在request对象中,request与Django自己的不一样,rest的request将数据封装到了 request.query_params,属性中,可以使用get获取。
第二:url的参数动态值怎么取?
在请求中,我们传的值都在**kwargs里,直接获取即可,记得用get。
想查看更多内容,请访问 http://www.hairuinet.com
Djano之写api使用django_rest_framework【海瑞博客】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。