django-rest-swagger的优化使用方法

yipeiwu_com6年前Python基础

如下所示:

requirements.txt
django==1.10.5

djangorestframework==3.5.3

django-rest-swagger==2.1.1

参考英文文档:

http://django-rest-swagger.readthedocs.io/en/latest/

使用swagger工具结合Django-rest-framework进行restful API的管理以及可视化显示的时候,由于swagger2.1以后不再使用yaml文档描述api,改而使用json描述,虽然swagger有着自动适配url扫描生成文档的能力,可是自动生成的文档并不详细,然而完全通过json文件描述所有的api,工作量比较大,且有的api也不需要详细描述,因而需要自定义api的json描述和自动扫描生成相结合。

实现如下:

swagger_views.py

# -*- coding: utf-8 -*-

import json
from collections import OrderedDict

from openapi_codec import OpenAPICodec
from openapi_codec.encode import generate_swagger_object
from coreapi.compat import force_bytes

from django.conf import settings

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator

from rest_framework_swagger.renderers import (
 SwaggerUIRenderer,
 OpenAPIRenderer
)


class SwaggerSchemaView(APIView):
 renderer_classes = [
  OpenAPIRenderer,
  SwaggerUIRenderer
 ]

 def load_swagger_json(self, doc):
  """
  加载自定义swagger.json文档
  """
  data = generate_swagger_object(doc)
  with open(settings.API_DOC_PATH) as s:
   doc_json = json.load(s, object_pairs_hook=OrderedDict)

  data['paths'].update(doc_json.pop('paths'))
  data.update(doc_json)
  return OpenAPICodec().decode(force_bytes(json.dumps(data)))

 def get(self, request):
  generator = SchemaGenerator(title='后端API文档',
         urlconf='chess_user.urls')
  schema = generator.get_schema(request=request)
  document = self.load_swagger_json(schema)

  return Response(document)

urls.py

from django.conf.urls import url, include
from django.conf.urls.static import static
from .swagger_views import SwaggerSchemaView


urlpatterns = [
 url(r'^api-doc/$', SwaggerSchemaView.as_view(), name='docs'),

settings.py

SWAGGER_SETTINGS = {
 'JSON_EDITOR': True,
 'LOGIN_URL': 'login',
 'LOGOUT_URL': 'logout',
}

API_DOC_PATH = os.path.join(BASE_DIR, "api-doc/swagger.json")

api-doc/swagger.json

{
 "paths": {
  "v1/user/profile/": {
   "get": {
    "tags": [
     "v1"
    ],
    "description": "用户profile\n",
    "responses": {
     "200": {
      "description": "OK",
      "schema": {
       "title": "User",
       "type": "object",
       "properties": {
        "username": {
         "type": "string"
        },
        "email": {
         "type": "string"
        },
        "phone_number": {
         "type": "string"
        }
       }
      }
     }
    }
   }
  }

 }
}

若有bug,欢迎指出!

以上这篇django-rest-swagger的优化使用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3在同一行内输入n个数并用列表保存的例子

最近在学习算法,经常遇到一行有多个数据,用空格或者','进行分割。最开始不懂,直接百度, n = input() n = int(n) list1 = [] list1 = inpu...

python实现计算倒数的方法

本文实例讲述了python实现计算倒数的方法。分享给大家供大家参考。具体如下: class Expr: def __add__(self, other): return P...

在python 中split()使用多符号分割的例子

调用re模块中的split()函数可以用多个符号进行分割 In [1]: import re In [2]: words = '我,来。上海?吃?上海菜' In [3]: wor...

基于wxpython开发的简单gui计算器实例

本文实例讲述了基于wxpython开发的简单gui计算器。分享给大家供大家参考。具体如下: # wxCalc1 a simple GUI calculator using wxPyt...

Python的log日志功能及设置方法

引入:Python中有个logging模块可以完成相关信息的记录,在debug时用它往往事半功倍 一、日志级别(从低到高): DEBUG :详细的信息,通常只出现在诊断问题上 INFO:...