Django REST framework (八)生成api接口文档

  • A+
所属分类:Django REST framework

原创:www.pythonfans.cn

安装搭建环境:

安装以及项目搭建参考:Django REST framework (一)安装以及django项目创建

继承上一篇viewsets高级用法的环境: https://www.pythonfans.cn/archives/89.html

安装coreapi模块

pip install coreapi

url配置(覆盖上一篇文章的url)

from rest_framework.routers import DefaultRouter
from django.urls import include
from rest_framework.documentation import include_docs_urls
route = DefaultRouter()
route.register('idc6',idc6,base_name="idc") #注册一个url资源管理idc,调用视图是idc6
urlpatterns = [
    path('', include(route.urls)),  #引入api route页面,route.urls
    path('docs/',include_docs_urls("ly_ops接口文档"))
]

修改views.py,新增注释(接口文档使用)

from .models import Idc
from .serializers import IdcSerializer

from rest_framework.viewsets import ModelViewSet
#ModelViewSet:读写,实现了mixins下面增删改查
#ReadOnlyModelViewSet:只读,只实现了只读
class idc6(ModelViewSet):
    """
    list:
        查看所有的Idc信息
    create:
        创建一个idc
    retrieve:
        获取一个idc资源
    destroy:
        删除一个idc资源
    uodate:
        更新一个idc资源
    """
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

访问http://127.0.0.1:8000/docs/

Django REST framework (八)生成api接口文档

优化serialzers序列化

from  rest_framework import serializers
from .models import Idc

class IdcSerializer(serializers.Serializer):
    """
    IDC序列化
    """
    id = serializers.IntegerField(read_only=True) 
    name = serializers.CharField(required=True, 
                                 max_length=22,
                                 label="IDC名",  
                                 help_text="IDC名字", 
                                 error_messages = { 
                                     "blank":"必须穿入",
                                     "required":"字段必须传入" })
    email = serializers.EmailField(required=True)
    address = serializers.CharField(required=True)
    phone = serializers.IntegerField(required=True)

    def create(self, validated_data):
        return  Idc.objects.create(**validated_data)
    def update(self, instance, validated_data):
        #instance代表是原始数据,validated_data最新数据
        instance.name = validated_data.get("name",instance.name)
        instance.email = validated_data.get("email", instance.email)
        instance.address = validated_data.get("address", instance.address)
        instance.phone = validated_data.get("phone", instance.phone)
        instance.save()
        return instance

说明:

read_only,只读,对提交数据忽略
required:必须传
label : 列名,在api root文档会显示字段名
help_text : 在doc文档的Description会显示对应信息
error_messages :自定义错误消息 。 blank , required 用户如果没有提交字段会提示中文让用户传入

报错解决:

报错:'AutoSchema' object has no attribute 'get_link'

解决:setting.py里面新增

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: