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


Posted in Python onAugust 29, 2019

如下所示:

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 相关文章推荐
Python生成器以及应用实例解析
Feb 08 Python
python编程嵌套函数实例代码
Feb 11 Python
Python3.6简单的操作Mysql数据库的三个实例
Oct 17 Python
python3利用ctypes传入一个字符串类型的列表方法
Feb 12 Python
实例详解python函数的对象、函数嵌套、名称空间和作用域
May 31 Python
python发送多人邮件没有展示收件人问题的解决方法
Jun 21 Python
Python队列RabbitMQ 使用方法实例记录
Aug 05 Python
pytorch .detach() .detach_() 和 .data用于切断反向传播的实现
Dec 27 Python
推荐8款常用的Python GUI图形界面开发框架
Feb 23 Python
Python中猜拳游戏与猜筛子游戏的实现方法
Sep 04 Python
scrapy-redis分布式爬虫的搭建过程(理论篇)
Sep 29 Python
Python的collections模块真的很好用
Mar 01 Python
使用虚拟环境打包python为exe 文件的方法
Aug 29 #Python
python实现最大优先队列
Aug 29 #Python
django连接oracle时setting 配置方法
Aug 29 #Python
python线程的几种创建方式详解
Aug 29 #Python
python fuzzywuzzy模块模糊字符串匹配详细用法
Aug 29 #Python
python多线程分块读取文件
Aug 29 #Python
用sqlalchemy构建Django连接池的实例
Aug 29 #Python
You might like
JavaScript中void(0)的具体含义解释
2007/02/27 Javascript
jquery 选择器部分整理
2009/10/28 Javascript
node中socket.io的事件使用详解
2014/12/15 Javascript
JavaScript控制网页平滑滚动到指定元素位置的方法
2015/04/17 Javascript
ajax图片上传,图片异步上传,更新实例
2016/12/30 Javascript
vue使用$emit时,父组件无法监听到子组件的事件实例
2018/02/26 Javascript
vue实现2048小游戏功能思路详解
2018/05/09 Javascript
Vuex中的State使用介绍
2019/01/19 Javascript
js实现一款简单踩白块小游戏(曾经很火)
2019/12/02 Javascript
JS通用方法触发点击事件代码实例
2020/02/17 Javascript
Javascript基于OOP实实现探测器功能代码实例
2020/08/26 Javascript
[01:30]我们共输赢 完美世界城市挑战赛开启全新赛季
2019/04/19 DOTA
python 从远程服务器下载东西的代码
2013/02/10 Python
python strip()函数 介绍
2013/05/24 Python
JPype实现在python中调用JAVA的实例
2017/07/19 Python
python读取图片并修改格式与大小的方法
2018/07/24 Python
python爬取微信公众号文章
2018/08/31 Python
对python实现模板生成脚本的方法详解
2019/01/30 Python
python遍历文件目录、批量处理同类文件
2019/08/31 Python
python3 动态模块导入与全局变量使用实例
2019/12/22 Python
Python装饰器用法与知识点小结
2020/03/09 Python
浅谈python3 构造函数和析构函数
2020/03/12 Python
selenium3.0+python之环境搭建的方法步骤
2021/02/01 Python
CSS3教程(9):设置RGB颜色
2009/04/02 HTML / CSS
利用CSS3的特性改变文本选中时的颜色
2013/09/11 HTML / CSS
ZWILLING双立人英国网上商店:德国刀具锅具厨具品牌
2018/05/15 全球购物
const char*, char const*, char*const的区别是什么
2014/07/09 面试题
高校学生干部的自我评价分享
2013/11/04 职场文书
关于读书的演讲稿
2014/05/07 职场文书
监督检查工作方案
2014/05/28 职场文书
2014领导班子四风剖析对照检查材料思想汇报
2014/09/20 职场文书
党员批评与自我批评总结
2014/10/15 职场文书
女人创业励志语录,句句蕴含能量,激发你的潜能
2019/08/20 职场文书
uwsgi+nginx代理Django无法访问静态资源的解决
2021/05/10 Servers
一篇文章带你复习java知识点
2021/06/28 Java/Android
python常见的占位符总结及用法
2021/07/02 Python