1. 什么是REST

  • REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
  • REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行标识,客户端应用通过URL来获取资源的表征,获得这些表征致使这些应用转变状态
  • 所有的数据,不过是通过网络获取的还是操作(增删改查)的数据,都是资源,将一切数据视为资源是REST区别与其他架构风格的最本质属性
  • 对于REST这种面向资源的架构风格,有人提出一种全新的结构理念,即:面向资源架构(ROA:Resource Oriented Architecture)

设计参考:http://www.ruanyifeng.com/blog/2014/05/restful_api.html

2. 目前如何实现 REST API ?

按照规则,根据不同的请求方式做出不同的处理,并且返回内容以及相应状态码

3. 什么是 Django REST framework

Django REST framework是一个基于Django开发的app,用于快速搭建REST API。

安装:

pip3 install djangorestframework

a. 快速使用

1. 注册APP

 1 from rest_framework import routers
 2 from . import views
 3 
 4 
 5 router = routers.DefaultRouter()
 6 router.register(r'users', views.UserInfoViewSet)
 7 
 8 urlpatterns = [
 9     url(r'^', include(router.urls)),
10 ]

2. 注册路由

 1 from rest_framework import viewsets
 2 from . import models
 3 from . import serializers
 4 
 5 # ########### 1. 基本处理方式 ###########
 6 
 7 class UserInfoViewSet(viewsets.ModelViewSet):
 8     """
 9     API endpoint that allows users to be viewed or edited.
10     """
11     queryset = models.UserInfo.objects.all().order_by('-id')
12     serializer_class = serializers.UserInfoSerializer

3. 编写ViewSet,视图函数

1 from rest_framework import serializers
2 from . import models
3 
4 class UserInfoSerializer(serializers.HyperlinkedModelSerializer):
5     class Meta:
6         model = models.UserInfo
7         # fields = ('id', 'username', 'pwd','ug') # fields = '__all__'
8         exclude = ('ug',)
9         depth = 1  # 0<=depth<=10

4. 编写serializers,form验证以及数据库操作

PS:最终访问路径

1 [GET]          http://127.0.0.1:8000/api/users/
2 [POST]         http://127.0.0.1:8000/api/users/
3 [GET]          http://127.0.0.1:8000/api/users/7/
4 [PUT]          http://127.0.0.1:8000/api/users/7/
5 [DELETE]       http://127.0.0.1:8000/api/users/7/

b. 基于CBV

1 from django.conf.urls import url,include
2 from django.contrib import admin
3 from . import views
4 
5 urlpatterns = [
6     url(r'^users/$', views.UserList.as_view()),
7     url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
8 ]

1. URL

 1 from rest_framework.views import APIView
 2 from rest_framework.response import Response
 3 from rest_framework.request import Request
 4 from rest_framework.parsers import JSONParser
 5 from . import models
 6 from . import serializers
 7 
 8 
 9 class UserList(APIView):
10     def get(self, request, *args, **kwargs):
11         user_list = models.UserInfo.objects.all()
12         serializer = serializers.MySerializer(instance=user_list, many=True)
13         return Response(serializer.data)
14 
15     def post(self, request, *args, **kwargs):
16         data = JSONParser().parse(request)
17         serializer = serializers.MySerializer(data=data)
18         if serializer.is_valid():
19             # print(serializer.data)
20             # print(serializer.errors)
21             # print(serializer.validated_data)
22             # 如果有instance,则执行update方法;否则,执行create
23             serializer.save()
24             return Response(serializer.data, status=201)
25         return Response(serializer.errors, status=400)
26 
27 
28 class UserDetail(APIView):
29     def get(self, request, *args, **kwargs):
30         obj = models.UserInfo.objects.filter(pk=kwargs.get('pk')).first()
31         serializer = serializers.MySerializer(obj)
32         return Response(serializer.data)
33 
34     def delete(self, request, *args, **kwargs):
35         obj = models.UserInfo.objects.filter(pk=kwargs.get('pk')).first()
36         obj.delete()
37         return Response(status=204)
38 
39     def put(self, request, *args, **kwargs):
40         data = JSONParser().parse(request)
41         obj = models.UserInfo.objects.filter(pk=kwargs.get('pk')).first()
42         serializer = serializers.MySerializer(obj, data=data)
43         if serializer.is_valid():
44             serializer.save()
45             return Response(serializer.data)
46         return Response(serializer.errors, status=400)

2. 编写视图函数

 1 from rest_framework import serializers
 2 from rest_framework.exceptions import ValidationError
 3 from . import models
 4 
 5 
 6 class MySerializer(serializers.Serializer):
 7     id = serializers.IntegerField(read_only=True)
 8     username = serializers.CharField(required=False, allow_blank=True, max_length=100)
 9     pwd = serializers.CharField()
10 
11     def validate_username(self, value):
12         if value == '中国':
13             raise ValidationError('用户名中存在敏感字符')
14         return value
15 
16     def validate_pwd(self, value):
17         print(value)
18         return value
19 
20     def validate(self, attrs):
21         print(attrs)
22         return attrs
23 
24     def create(self, validated_data):
25         """
26         当执行save方法时,自动调用。instance未传值
27         :param validated_data:
28         :return:
29         """
30         print(validated_data)
31         return models.UserInfo.objects.create(**validated_data)
32 
33     def update(self, instance, validated_data):
34         """
35         当执行save方法时,自动调用。instance传值
36         :param instance:
37         :param validated_data:
38         :return:
39         """
40         instance.username = validated_data.get('username', instance.username)
41         instance.save()
42         return instance

3. 编写serializer

c. 基于FBV

1 from django.conf.urls import url,include
2 from django.contrib import admin
3 from . import views
4 
5 urlpatterns = [
6     url(r'^users/$', views.user_list),
7     url(r'^users/(?P<pk>[0-9]+)/$', views.user_detail),
8 ]

1. URL

 1 from django.http import JsonResponse,HttpResponse
 2 from rest_framework.response import Response
 3 from rest_framework.parsers import JSONParser
 4 from rest_framework.decorators import api_view
 5 from .serializers import MySerializer
 6 from . import models
 7 
 8 @api_view(['GET',"POST"])
 9 def user_list(request):
10     """
11     List all code snippets, or create a new snippet.
12     """
13     if request.method == 'GET':
14         user_list = models.UserInfo.objects.all()
15         serializer = MySerializer(user_list,many=True)
16         return Response(serializer.data)
17 
18     elif request.method == 'POST':
19         data = JSONParser().parse(request)
20         serializer = MySerializer(data=data)
21         if serializer.is_valid():
22             print(serializer.data)
23             print(serializer.errors)
24             print(serializer.validated_data)
25             # 如果有instance,则执行update方法;否则,执行create
26             serializer.save()
27             return Response(serializer.data, status=201)
28         return Response(serializer.errors, status=400)
29 
30 @api_view(['GET',"POST","PUT"])
31 def user_detail(request, pk):
32     """
33     Retrieve, update or delete a code snippet.
34     """
35 
36     obj = models.UserInfo.objects.filter(pk=pk).first()
37     if not obj:
38         return HttpResponse(status=404)
39 
40     if request.method == 'GET':
41         serializer = MySerializer(obj)
42         # return JsonResponse(serializer.data,json_dumps_params={'ensure_ascii':False},content_type='application/json;charset=utf-8')
43         return Response(serializer.data)
44 
45     elif request.method == 'PUT':
46         data = JSONParser().parse(request)
47         serializer = MySerializer(obj, data=data)
48         if serializer.is_valid():
49             serializer.save()
50             return Response(serializer.data)
51         return Response(serializer.errors, status=400)
52 
53     elif request.method == 'DELETE':
54         obj.delete()
55         return Response(status=204)

2. 视图函数

 1 from rest_framework import serializers
 2 from rest_framework.exceptions import ValidationError
 3 from . import models
 4 
 5 
 6 class MySerializer(serializers.Serializer):
 7     id = serializers.IntegerField(read_only=True)
 8     username = serializers.CharField(required=False, allow_blank=True, max_length=100)
 9     pwd = serializers.CharField()
10 
11     def validate_username(self, value):
12         if value == '中国':
13             raise ValidationError('用户名中存在敏感字符')
14         return value
15 
16     def validate_pwd(self, value):
17         print(value)
18         return value
19 
20     def validate(self, attrs):
21         print(attrs)
22         return attrs
23 
24     def create(self, validated_data):
25         """
26         当执行save方法时,自动调用。instance未传值
27         :param validated_data:
28         :return:
29         """
30         print(validated_data)
31         return models.UserInfo.objects.create(**validated_data)
32 
33     def update(self, instance, validated_data):
34         """
35         当执行save方法时,自动调用。instance传值
36         :param instance:
37         :param validated_data:
38         :return:
39         """
40         instance.username = validated_data.get('username', instance.username)
41         instance.save()
42         return instance

3. 编写serializer

d. 权限控制

1 REST_FRAMEWORK = {
2     'DEFAULT_PERMISSION_CLASSES': [
3         'permissi.MyPermission',
4     ]
5 }

1. settings配置文件

 1 class MyPermission(object):
 2     """
 3     A base class from which all permission classes should inherit.
 4     """
 5 
 6     def has_permission(self, request, view):
 7         """
 8         Return `True` if permission is granted, `False` otherwise.
 9         """
10 
11         return True
12 
13     def has_object_permission(self, request, view, obj):
14         return True

2. 权限控制

 

 

转载自银角大王: