rest_framework框架是基于Django实现的一个RESTful风格的API框架,之前介绍过restful风格,可以参考这篇文章---->传送门
pip install djangorestframework
在installed_apps中注册
INSTALLED_APPS = [
...,
'rest_framework',
]
在setting.py 配置
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': ( # 默认响应渲染类
# 'rest_framework.schemas.AutoSchema',
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'
)
}
在app中新建serializers.py文件和models.py,views.py同级
在里面定义序列化器
class HrefInfoModelSerializer(serializers.ModelSerializer):
class Meta:
model = Href
fields = '__all__'
def create(self, validated_data):
return Href.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.url = validated_data.get('url', instance.url)
instance.save()
return instance
在views.py引入ModelViewSet,从serializers引入我们实现的序列化器
from rest_framework.viewsets import ViewSet, ModelViewSet
from .serializers import HrefInfoModelSerializer
在views.py实现我们的逻辑处理,rest_framework为我们提供了最基本的增删改查,我们可以自己实现其他的功能,比如单个查询指定的数据。
from rest_framework import serializers
from .models import Href
class HrefViewSet(ModelViewSet):
parser_classes = [JSONParser, FormParser]
"""视图集"""
queryset = models.Href.objects.all()
serializer_class = HrefInfoModelSerializer
# 搜索
search_fields = ('id', 'name')
# 添加链接
@action(methods=['post'], detail=False)
@csrf_exempt
def add_href(self, request, *args, **kwargs):
name = request.data.get('name', None)
if name:
print(name)
obj = models.Href.objects.filter(name=name).first()
if obj:
return JsonResponse({
'status': '1001',
'msg': '已经存在此链接名称'
})
else:
serializer = HrefInfoModelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse({
'status': '1000',
'msg': '添加成功'
})
else:
return JsonResponse({
'status': '1002',
'msg': '插入数据不合法'
})
else:
return Response(status=status.HTTP_204_NO_CONTENT)
pass
# 删除链接
@action(methods=['delete'], detail=False)
@csrf_exempt
def multiple_delete(self, request, *args, **kwargs):
count = 0
delete_id = request.data.get('id', None)
print(delete_id)
if not delete_id:
return Response(status=status.HTTP_404_NOT_FOUND)
for i in delete_id.split(','):
obj = models.Href.objects.filter(id=i).first()
if obj:
obj.delete()
count = count + 1
else:
return Response(status=status.HTTP_204_NO_CONTENT)
return JsonResponse({
'code': 200,
'msg': '删除成功',
'num': count
})
# 获取单个链接信息
@action(methods=['get'], detail=False)
@csrf_exempt
def single_href(self, request, *args, **kwargs):
query_name = request.data.get('name', None)
print(query_name)
if not query_name:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
href = models.Href.objects.all().filter(name=query_name)
serializer = HrefInfoModelSerializer(instance=href, many=True)
print(serializer.data)
return JsonResponse({
'code': 2010,
'msg': '查询成功',
'data': serializer.data
})
# 修改信息
@action(methods=['put'], detail=False)
@csrf_exempt
def edit_href(self, request, *args, **kwargs):
name = request.data.get('name', None)
if name:
obj = models.Href.objects.filter(name=name).first()
serializer = HrefInfoModelSerializer(instance=obj, data=request.data, partial=True)
if serializer.is_valid():
serializer.save(update_fields=['name', 'id'])
return JsonResponse({
'code': 200,
'msg': '更新成功',
})
else:
return JsonResponse({
'code': 201,
'msg': '更新失败',
})
else:
return Response(status.HTTP_204_NO_CONTENT)
在urls.py引入路径,rest_framework提供了路径匹配SimpleRouter,我们不需要一点一点的书写path了
from rest_framework.routers import DefaultRouter, SimpleRouter
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
router = SimpleRouter()
router.register(r'href', views.HrefViewSet) # 注册路由
urlpatterns += router.urls # 把生成好的路由拼接到urlpatterns