标签:不同的 contain turn min update 使用 rom ret required
1. 什么是REST
设计参考:http://www.ruanyifeng.com/blog/2014/05/restful_api.html
2. 目前如何实现 REST API ?
按照规则,根据不同的请求方式做出不同的处理,并且返回内容以及相应状态码
3. 什么是 Django REST framework?
Django REST framework是一个基于Django开发的app,用于快速搭建REST API。
安装:
1
|
pip3 install djangorestframework |
a. 快速使用
INSTALLED_APPS = [ ... ‘rest_framework‘, ]
from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r‘users‘, views.UserInfoViewSet) urlpatterns = [ url(r‘^‘, include(router.urls)), ]
from rest_framework import viewsets from . import models from . import serializers # ########### 1. 基本处理方式 ########### class UserInfoViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = models.UserInfo.objects.all().order_by(‘-id‘) serializer_class = serializers.UserInfoSerializer
from rest_framework import serializers from . import models class UserInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.UserInfo # fields = (‘id‘, ‘username‘, ‘pwd‘,‘ug‘) # fields = ‘__all__‘ exclude = (‘ug‘,) depth = 1 # 0<=depth<=10
PS:最终访问路径
1
2
3
4
5
|
[GET] http: / / 127.0 . 0.1 : 8000 / api / users / [POST] http: / / 127.0 . 0.1 : 8000 / api / users / [GET] http: / / 127.0 . 0.1 : 8000 / api / users / 7 / [PUT] http: / / 127.0 . 0.1 : 8000 / api / users / 7 / [DELETE] http: / / 127.0 . 0.1 : 8000 / api / users / 7 / |
b. 基于CBV
from django.conf.urls import url,include from django.contrib import admin from . import views urlpatterns = [ url(r‘^users/$‘, views.UserList.as_view()), url(r‘^users/(?P<pk>[0-9]+)/$‘, views.UserDetail.as_view()), ]
复制代码 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import JSONParser from . import models from . import serializers class UserList(APIView): def get(self, request, *args, **kwargs): user_list = models.UserInfo.objects.all() serializer = serializers.MySerializer(instance=user_list, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): data = JSONParser().parse(request) serializer = serializers.MySerializer(data=data) if serializer.is_valid(): # print(serializer.data) # print(serializer.errors) # print(serializer.validated_data) # 如果有instance,则执行update方法;否则,执行create serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) class UserDetail(APIView): def get(self, request, *args, **kwargs): obj = models.UserInfo.objects.filter(pk=kwargs.get(‘pk‘)).first() serializer = serializers.MySerializer(obj) return Response(serializer.data) def delete(self, request, *args, **kwargs): obj = models.UserInfo.objects.filter(pk=kwargs.get(‘pk‘)).first() obj.delete() return Response(status=204) def put(self, request, *args, **kwargs): data = JSONParser().parse(request) obj = models.UserInfo.objects.filter(pk=kwargs.get(‘pk‘)).first() serializer = serializers.MySerializer(obj, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400)
from rest_framework import serializers from rest_framework.exceptions import ValidationError from . import models class MySerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) username = serializers.CharField(required=False, allow_blank=True, max_length=100) pwd = serializers.CharField() def validate_username(self, value): if value == ‘中国‘: raise ValidationError(‘用户名中存在敏感字符‘) return value def validate_pwd(self, value): print(value) return value def validate(self, attrs): print(attrs) return attrs def create(self, validated_data): """ 当执行save方法时,自动调用。instance未传值 :param validated_data: :return: """ print(validated_data) return models.UserInfo.objects.create(**validated_data) def update(self, instance, validated_data): """ 当执行save方法时,自动调用。instance传值 :param instance: :param validated_data: :return: """ instance.username = validated_data.get(‘username‘, instance.username) instance.save() return instance
c. 基于CBV
from django.conf.urls import url,include from django.contrib import admin from . import views urlpatterns = [ url(r‘^users/$‘, views.user_list), url(r‘^users/(?P<pk>[0-9]+)/$‘, views.user_detail), ]
标签:不同的 contain turn min update 使用 rom ret required
原文地址:http://www.cnblogs.com/xuaijun/p/7283132.html