django restful API

2018-05-12  本文已影响0人  裴general

摘要

什么是rest:REST是所有Web应用都应该遵守的架构设计指导原则
rest设计有点: 1.客户端-服务端分离 2..无状态(Stateless):从客户端的每个请求要包含服务器所需要的所有信息 3.缓存(Cachable):服务器返回信息必须被标记是否可以缓存,如果缓存,客户端可能会重用之前的信息发送请求 4.统一接口优点:提高交互的可见性,鼓励单独改善组件 5.支持按需代码(Code-On-Demand 可选)
REST是面向资源进行的,而资源是通过URI进行暴露的。
REST同一个资源的一组不同的操作

1.django restful流程

models ----> Serialiers --->viewsets ---->routers --->urls ---->filters

2.配置settings.py文件

(1)INSTALLED_APPS 追加 rest_freamwork


image.png

(2)配置restful API的返回结果

REST_FRAMEWORK = {
    # 分页
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 2,

    # 设置搜索---将版本换为3.4.6
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
                               'rest_framework.filters.SearchFilter'),

    # 返回结构自定义
    'DEFAULT_RENDERER_CLASSES': (
        'utils.RenderResponse.CustomJsonRenderer',
    )
}

3.配置应用文件urls.py,设置路由

from rest_framework.routers import SimpleRouter
from django.conf.urls import url

router = SimpleRouter()
router.register(r'student', views.Studentsedit)
urlpatterns += router.urls

4.views.py文件中配置相关方法 ,实现CRUD

这里的方法要使用class

from rest_framework import mixins, viewsets
from stu.serializers import StudentSerializer
from rest_framework.response import Response
from stu.filters import StuFilter

class Studentsedit(mixins.ListModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.CreateModelMixin,
                   viewsets.GenericViewSet):

    # 查询所有信息
    queryset = Student.objects.all()
    # 序列化
    serializer_class = StudentSerializer

    # 过滤
    filter_class = StuFilter

    # 重定义获得  删除后筛选出删除状态为0的,并且对其从大到小进行排序
    def get_queryset(self):
        query = self.queryset
        return query.filter(s_delete=0).order_by('-id')

    # 重定义删除  实现软删除  使数据库中的删除状态转变, 实际上数据依然留在数据库中
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.s_delete = 1
        instance.save()
        return Response({'msg': '删除成功', 'code': 200})

5.应用文件下新建过滤filters.py 和 序列化 serializers.py文件

(1)序列化 serializers
序列化的数据是json格式

from rest_framework import serializers
from stu.models import Student


class StudentSerializer(serializers.ModelSerializer):
# 重定义错误信息返回名
    s_name = serializers.CharField(error_messages={
        'blank': '用户名不能为空',
        'max_length': '用户名不能超过10个字符串'
    }, max_length=10)

    s_tel = serializers.CharField(error_messages={
        'blank': '电话号码不能为空'
    })

# 传递的字段
    class Meta:
        model = Student
        fields = ['id', 's_name', 's_tel', 's_yuwen', 's_status', 's_operate_time']

# 显示实例的关联的地址
    def to_representation(self, instance):

        data = super().to_representation(instance)
        try:
            data['s_addr'] = instance.studentinfo.i_addr
        except Exception as e:
            data['s_addr'] = ''
        data['s_status'] = dict(Student.STATUS)[data['s_status']]

        return data

(2)定义过滤

import django_filters
from rest_framework import filters
from stu.models import Student


class StuFilter(filters.FilterSet):

    name = django_filters.CharFilter('s_name', lookup_expr='icontains')
    tel = django_filters.CharFilter('s_tel')
    status = django_filters.CharFilter('s_status')
    operate_time_min = django_filters.DateTimeFilter('s_operate_time', lookup_expr='gte')
    operate_time_max = django_filters.DateTimeFilter('s_operate_time', lookup_expr='lte')
    yuwen_min = django_filters.NumberFilter('s_yuwen', lookup_expr='gte')
    yuwen_max = django_filters.NumberFilter('s_yuwen', lookup_expr='lte')


    class Meta:
        model = Student
        fields = ['s_name', 's_tel', 's_yuwen', 's_status', 's_operate_time']

6.查询

可以通过网页直接查询, 也可以通过postman软件来进行操作

上一篇下一篇

猜你喜欢

热点阅读