zoukankan      html  css  js  c++  java
  • 一.3.序列化使用之idc资源与api文档

     前后端分离,前端写前端的,后端写后端的,但是它们中间得有一个api文档

    1.idc资源

    (1)models.py:

    from django.db import models
    
    class Idc(models.Model):
        name =  models.CharField("机房名",max_length=32)
        address = models.CharField("机房地址",max_length=200)
        phone = models.CharField("机房联系电话",max_length=15)
        email = models.EmailField("机房联系email")
        letter = models.CharField("idc字母简称",max_length=5)
        def __str__(self):
            return self.name
        class Meta:
            db_table = 'resources_idc'

    (2)views.py:

    from .models import Idc
    from .serializers import IdcSerializer
    from rest_framework import viewsets
    
    ##########################  版本七   ############################
    class IdcViewset(viewsets.ModelViewSet):   --->modelviewset继承了所有的操作方法
        """
        retrieve:返回指定Idc信息
         list:返回指定Idc列表
         update:更新Idc信息
         destroy:删除idc记录
         create:创建idc记录
         partial_update:更新部分字段
        """
        queryset = Idc.objects.all()
        serializer_class = IdcSerializer

    (3)serializer.py:

    from rest_framework import serializers
    from .models import Idc
    class IdcSerializer(serializers.Serializer):   -->注意label是测试页面显示中文,help_text是接口文档页面显示中文
        """
        Idc 序列化类
        """
        id      = serializers.IntegerField(read_only=True)  #只读的,即忽略可不传
        name    = serializers.CharField(required=True,max_length=32, label="机房名称", help_text="机房名称")  #意思是提交数据时此字段必须填且不能为空
        address = serializers.CharField(required=True,max_length=256, label="机房地址", help_text="机房地址")
        phone   = serializers.CharField(required=True,max_length=15, label="联系电话", help_text="联系电话")
        email   = serializers.EmailField(required=True, label="email", help_text="email")
        letter  = serializers.CharField(required=True,max_length=5, label="字母简称", help_text="字母简称")
    
        def create(self, validated_data):
            return Idc.objects.create(**validated_data)
        def update(self, instance, validated_data): #对已经验证过的非常干净的数据进行修改,instance是当前的对象
            instance.name = validated_data.get("name", instance.name)  #哪些字段可以修改,且默认名是
            instance.address = validated_data.get("address", instance.address)
            instance.phone = validated_data.get("phone", instance.phone)
            instance.email = validated_data.get("email", instance.email)
            instance.save()  #保存
            return instance  #返回

    (4)urls.py:

    from django.conf.urls import include, url
    from django.contrib import admin
    from rest_framework.routers import DefaultRouter
    from idcs.views import IdcViewset
    from apps.users.views import UserViewset
    
    route = DefaultRouter()
    route.register("idcs", IdcViewset, basename="idcs")
    #注册时三个参数:资源定位符,类,别名
    route.register("users", UserViewset, basename="users")
    urlpatterns = [
        url(r'^', include(route.urls)),
    ]

    (5)改错误提示为中文

    运行后可以看到接口测试页面如下效果:

    2.编写api文档

    (python36env) [vagrant@CentOS7 devops]$ pip install coreapi

    (python36env) [vagrant@CentOS7 devops]$ pip install coreapi-cli

    (1)devops/urls.py中:

    from django.conf.urls import include, url
    from django.contrib import admin
    from rest_framework.routers import DefaultRouter
    from idcs.views import IdcViewset
    from apps.users.views import UserViewset
    from rest_framework.documentation import include_docs_urls
    
    route = DefaultRouter()
    route.register("idcs", IdcViewset, basename="idcs")
    #注册时三个参数:资源定位符,类,别名
    route.register("users", UserViewset, basename="users")
    urlpatterns = [
        url(r'^', include(route.urls)),
        url(r'^docs/', include_docs_urls("lizhihua运维平台接口文档"))
    ]

    报错:
    EST framework可以自动帮助我们生成接口文档。REST framewrok生成接口文档需要coreapi库的支持。在访问生成的接口文档时,可能会发生如下错误:
    AttributeError: 'AutoSchema' object has no attribute 'get_link'异常处理
    解决:在配置文件settings.py中重新指定schema_class的配置:
    REST_FRAMEWORK = {
      'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    # 新版drf schema_class默认用的是rest_framework.schemas.openapi.AutoSchema

    }

    运行后效果如下:

  • 相关阅读:
    Vue.js 章6 v-model与表单
    Vue.js 简单购物车开发
    Vue.js实战 章五:内置指令
    Vue stage3
    Vue初接触 stage1
    前端代码的一些恶优化
    websocket介绍 以及 vue websocket使用案例
    回忆一下跨域
    如何使用Flexible这样的一库来完成H5页面的终端适配
    css 输入px单位的数值 直接转换为rem的插件
  • 原文地址:https://www.cnblogs.com/dbslinux/p/13091382.html
Copyright © 2011-2022 走看看