django开发-使用django_rest_swagger自动生成接口文档

今天介绍一下在django开发中如何使用django_rest_swagger自动生成接口文档。

1.首先安装相关包


pip install djangorestframework
pip install django-rest-swagger
pip install coreapi

2.在settings.py中配置restframework和restswagger


INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_swagger',
]

SWAGGER_SETTINGS = {
    "SECUROTY_DEFINITIONS": {
        "basic": {
            'type': 'basic'
        }
    },
    "APIS_SORTER": 'alpha',
    "JSON_EDITOR": True,
    "OPERATIONS_SORTER": 'alpha',
    "VALIDATOR_URL": None,
    "SHOW_REQUEST_HEADERS": True,
}

restswagger的配置信息可以查看官网说明:
https://django-rest-swagger.readthedocs.io/en/latest/settings/

下面的步骤使用了rest_framework.schema和coreapi,可以看一下rest_framework官网关于schemas的介绍:https://www.django-rest-framework.org/api-guide/schemas/

3.在项目的urls.py中配置


"""api URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

from django.conf.urls import url
from create_api import views


from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
schema_view = get_schema_view(title="Docs API", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])


urlpatterns = [
    url(r'^docs/', schema_view, name="docs"),
    path('admin/', admin.site.urls),
    path('api/', include("create_api.urls"))
]

4.app/views.py:


import coreapi
from .models import UserModel
from .serializers import UserSerializers
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.schemas import AutoSchema


# 定义一个类,继承自AutoSchema
class Test01Schema(AutoSchema):
    def get_manual_fields(self, path, method):
        """ 重写该方法,根据不同的方法不同的参数 """
        print("method:", method)
        if method == "POST":
            manual_fields = [
                coreapi.Field(name='name', required=True, location='form', description='', type='string'),
                coreapi.Field(name='age', required=True, location='form', description='', type='int'),
            ]
            return manual_fields
        elif method == "GET":
            manual_fields = [
                coreapi.Field(name='id', required=False, location='path', description='', type='int'),
            ]
            return manual_fields


class Test01View(APIView):


    schema = Test01Schema(
        manual_fields=[
            coreapi.Field(name='name', required=False, location='form', description='', type='string'),
            coreapi.Field(name='age', required=False, location='form', description='', type='int'),
        ]
    )

    def get(self, request, *args, **kwargs):
        """
        用户列表
        """
        user_objs = UserModel.objects.all()
        ser_user_obj = UserSerializers(instance=user_objs, many=True)
        ser_user = ser_user_obj.data
        return Response(dict(msg="OK", data=ser_user, code=10000))

    def post(self, request, *args, **kwargs):
        """
        新增用户
        """
        name = request.data.get("name")
        age = request.data.get("age")
        UserModel.objects.create(**{"name": name, "age": age})
        return Response(dict(msg="OK", code=10000))

5.启动项目后,访问http://127.0.0.1:8000/docs/,可以看到如下界面:

点击POST,再点击Try it out后,出现如下界面,可以在输入框中输入参数,并点击execute发送post请求,就可以收到服务器返回的响应体数据了

其中输入框中参数就是我们在Test01Schema中使用coreapi.Field定义的参数。

点击GET请求后,点击Try it out,再点击execute,我这边测试的返回结果如下:

这个功能与Postman中的功能是类似的。

今天就说到这,关于这一块还在研究中,以后还会更新。