zoukankan      html  css  js  c++  java
  • 0013 COREAPI自动生成接口文档

      CoreAPI是基于djangorestframework框架下的自动文档生成器,只要按DRF规则写的路由,CoreAPI就可以自动生成接口文档。

    1 编写DRF视图

      编写DRF视图有多种方式,

      本文本主要展示接口文档的自动生成。故编写一个最简单的视图。

    1.1 新增一个视图文件

      在Examples/views目录下,创建一个CoreAPI.py文件,其中创建了两个类,代码如下:

    from django.shortcuts import render
    from rest_framework.views import APIView
    from django.http import QueryDict
    from rest_framework.response import Response
    from rest_framework import status
    
    
    class CoreAPI(APIView):
        @classmethod
        def get(cls, request):
            """
            【功能描述】主要用于描述模块功能</br>
            【模块元素】用于描述模块中存在的相关元素</br>
            【返回参数】用于描述模块的返回参数</br>
            """
            return render(request, 'exp-home.html')
    
        @classmethod
        def post(cls, request):
            """
            【功能描述】用于保存表</br>
            【返回参数】用于返回模块的返回参数。</br>
            """
            username = request.POST.get('user')
            data = QueryDict(request.body.decode("utf-8"), encoding="utf-8").dict()
            return Response(data, status=status.HTTP_200_OK)
    
    
    class LoginHome(APIView):
        @classmethod
        def get(cls, request):
            """
            返回登录页面。登录页面主要包括以下功能:</br>
            【快捷登录】</br>
                    
            包括四个元素手机号输入框,发送验证码按钮,验证码输入框,确定按钮</br>
            【密码登录】</br>
                    
            包括两个元素:1 用户名或手机号 2 密码</br>
            【找回密码】</br>
                    
            是一个找回密码的标签,用于跳转到找回密码页面
            """
            return render(request, 'exp-home.html')

    1.2 修改ExpHome.py视图文件

      之前ExpHome.py文件中,主要用于返回一个网页,是Django本身的类方法。继承来自View,只继承APIView改成DRF框架,就可以生成到接口文档中了。

    from django.views.generic import View
    from django.shortcuts import render
    from rest_framework.views import APIView
    
    
    class ExoHome(APIView):
        @classmethod
        def get(cls, request):
            """
            【功能描述】主要用于示例展示</br>
            【返回参数】返回用户请求的网页</br>
            """
            return render(request, 'exp-home.html')
    

    2 修改Examples分路由

    from django.urls import path
    from Applications.Examples.views import ExpHome, CoreAPI
    
    urlpatterns = [
        path('ExpHome/', ExpHome.ExoHome.as_view()),
        path('CoreAPI/', CoreAPI.CoreAPI.as_view()),
        path('LoginHome/', CoreAPI.LoginHome.as_view()),
    ]
    

    3 修改工程总路由

    from django.contrib import admin
    from django.urls import path, include
    from rest_framework.documentation import include_docs_urls
    
    DESCRIPTION = """
            包括仝恒绩效云所有接口文档。包括以下应用:
            1 Authentication:认证服务应用
            2 Organization: 组织机构应用
    """
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('Examples/', include('Applications.Examples.urls')),
        path('docs/', include_docs_urls(title='API接口文档', description=DESCRIPTION)),
    ]
    

    4 运行工程,就可以看到接口文档的效果了。

     5 编写继承类

      由于CoreAPI没有对于GET方法请求参数的描述,故需要先编写一个继承类,使得用户可以在序列化器中直接明确相应的备注。

      在GeneralTools下创建一个CustomSchema.py文件。内容如下:

    from rest_framework.schemas import AutoSchema
    
    
    class CustomSchema(AutoSchema):
        """
        自定义AutoSchema,为view手动添加注释
        """
    
        def get_manual_fields(self, path, method):
            """
            location有下列可选选项可以选:
            path 包含在模板化URI中。例如,url值/products/{product_code}/可以与"path"字段一起使用。
            query 包含在URL查询参数中。例如?search=sale。通常用于GET请求。
            form 包含在请求正文中,作为JSON对象或HTML表单的单个项目。例如{"colour": "blue", ...}。通常的POST,PUT和PATCH请求。"form"单个链接上可以包含多个字段。
            header 包含在请求头中,可以自定义。
            {
                'get': [
                    coreapi.Field(name="mobile", required=True, location="path", schema=coreschema.String(description='手机号')),
                    coreapi.Field(name="name", required=True, location="query", schema=coreschema.String(description='用户名')),
                    coreapi.Field(name="password", required=True, location="query", schema=coreschema.String(description='密码')),
                ],
                'post': [
                    coreapi.Field(name="mobile", required=True, location="path", schema=coreschema.String(description='手机号')),
                    coreapi.Field(name="subject", required=True, location="query", schema=coreschema.String(description='邮件主题')),
                    coreapi.Field(name="message", required=True, location="query", schema=coreschema.String(description='邮件正文')),
                    coreapi.Field(name="to_email", required=True, location="query", schema=coreschema.String(description='收件人')),
                ],
            }
            """
    
            # 可能是list,也可能是dict
            manual_fields = super(CustomSchema, self).get_manual_fields(path, method)
    
            if type(manual_fields) == list:
                return manual_fields
            else:
                # dict
                for k, v in self._manual_fields.items():
                    if method.lower() == k.lower():
                        return v
                else:
                    return []
    

     

  • 相关阅读:
    PostgreSQL操作问题(转载)
    psql执行的时候不输入密码的设定 (转载)
    项目管理——对事不对人(转载)
    软件项目经理应有的能力和素质(转载)
    Postgresql数据库的一些字符串操作函数
    8 of the best web design resource pages(转载)
    再谈:Word转PDF及SWF在线浏览——Flash Paper
    项目VS产品
    PostgreSQL+PostGIS的使用(转载)
    12+ open source projects for .NET you probably didn’t know about(转载)
  • 原文地址:https://www.cnblogs.com/dorian/p/12368614.html
Copyright © 2011-2022 走看看