Loading

Python REST

Django REST framework

1. 什么是REST

  • REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
  • REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行标识,客户端应用通过URL来获取资源的表征,获得这些表征致使这些应用转变状态
  • REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
  • 所有的数据,不过是通过网络获取的还是操作(增删改查)的数据,都是资源,将一切数据视为资源是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。

安装:

1
pip3 install djangorestframework

a. 快速使用

INSTALLED_APPS = [
    ...
    'rest_framework',
]
1.注册APP
from rest_framework import routers
from . import views


router = routers.DefaultRouter()
router.register(r'users', views.UserInfoViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]
2.注册路由
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
3.编写ViewSet,视图函数
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
4.编写serializers,form验证以及数据库操作

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()),
]
1.URL
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)
2.编写视图函数
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
3.编写serializers

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),
]
1.URL
from django.http import JsonResponse,HttpResponse
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from .serializers import MySerializer
from . import models

@api_view(['GET',"POST"])
def user_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        user_list = models.UserInfo.objects.all()
        serializer = MySerializer(user_list,many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = 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)

@api_view(['GET',"POST","PUT"])
def user_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """

    obj = models.UserInfo.objects.filter(pk=pk).first()
    if not obj:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = MySerializer(obj)
        # return JsonResponse(serializer.data,json_dumps_params={'ensure_ascii':False},content_type='application/json;charset=utf-8')
        return Response(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = MySerializer(obj, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=400)

    elif request.method == 'DELETE':
        obj.delete()
        return Response(status=204)
2.视图函数
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
3.编写serializers

d. 权限控制

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'permissi.MyPermission',
    ]
}
1.settings配置文件
class MyPermission(object):
    """
    A base class from which all permission classes should inherit.
    """

    def has_permission(self, request, view):
        """
        Return `True` if permission is granted, `False` otherwise.
        """

        return True

    def has_object_permission(self, request, view, obj):
        return True
2.权限控制
 - 全局配置
                Highcharts.setOptions({
                    global: {
                        useUTC: false
                    }
                });

            - 主配置
                var chart = new Highcharts.Chart('id1', {
                title: {
                    text: '不同城市的月平均气温',
                    x: 0
                },
                subtitle: {
                    text: '数据来源: WorldClimate.com',
                    x: 0
                },
                chart: {
                    events: {
                        load: function (e) {
                            // 图标加载时,执行的函数
                        }
                    }
                },
                credits: {
                    enable: true,
                    position: {
                        align: 'right',
                        verticalAlign: 'bottom'
                    },
                    text: '老男孩',
                    href: 'http://www.oldboyedu.com'
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle',
                    borderWidth: 1
                },

                xAxis: {
                    // categories: ['1.1', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    type: 'datetime',
                    labels: {
                        formatter: function () {
                            return Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.value);
                        },
                        rotation: 30
                    }

                },
                yAxis: {
                    title: {
                        text: '数值'
                    }
                },
                tooltip: {
                    valueSuffix: '',
                    xDateFormat: "%Y-%m-%d %H:%M:%S",
                    pointFormatter: function (e) {
                        var tpl = '<span style="color:' + this.series.color + '">●</span> ' + this.series.name + ': <b>' + this.y + '</b><br/>';
                        return tpl;
                    },
                    valueDecimals: 1,
                    useHTML: true
                },
                plotOptions: {
                    series: {
                        cursor: 'pointer',
                        events: {
                            click: function (event) {
                                // 点击某个指定点时,执行的事件
                                console.log(this.name, event.point.x, event.point.y);
                            }
                        }
                    }
                },
                series: [{
                    name: '东京',
                    // data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
                    data: [
                        [1501689804077.358, 8.0],
                        [1501689814177.358, 6.9],
                        [1501689824277.358, 16.9],
                        [1501689834377.358, 11.9]
                    ]
                },
                    {
                        name: '洛杉矶',
                        // data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
                        data: [
                            [1501689804077.358, 18.0],
                            [1501689814177.358, 16.9],
                            [1501689824277.358, 26.9],
                            [1501689834377.358, 9.9]
                        ]
                    }]
            });

            // chart.addSeries({name:'北京',data: [216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5]});
            // 参数:数值;是否重绘; isShift; 是否动画
            // chart.series[0].addPoint(18);
            // chart.series[0].addPoint([12]);
            // chart.series[0].addPoint([v.x, v.y]);
            // 参数:是否重绘
            // chart.series[0].remove(false);
            // 更新饼图
            // $('#id1').highcharts().series[0].data[0].update({x: 0, y: 100})
临时放一下

 

posted @ 2017-08-09 21:15  Meet~  阅读(283)  评论(0编辑  收藏  举报