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的Django框架中的QuerySets
Apr 20 Python
Python中threading模块join函数用法实例分析
Jun 04 Python
Python批量修改文本文件内容的方法
Apr 29 Python
Python写的一个定时重跑获取数据库数据
Dec 28 Python
Python实现打印螺旋矩阵功能的方法
Nov 21 Python
Python爬虫番外篇之Cookie和Session详解
Dec 27 Python
Python使用matplotlib简单绘图示例
Feb 01 Python
python爬虫_实现校园网自动重连脚本的教程
Apr 22 Python
判断python字典中key是否存在的两种方法
Aug 10 Python
基于python实现学生管理系统
Oct 17 Python
Python @property使用方法解析
Sep 17 Python
Django实现翻页的示例代码
May 24 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
Notice: Trying to get property of non-object problem(PHP)解决办法
2012/03/11 PHP
php实例分享之mysql数据备份
2014/05/19 PHP
php过滤htmlspecialchars() 函数实现把预定义的字符转换为 HTML 实体用法分析
2019/06/25 PHP
php实现网页上一页下一页翻页过程详解
2019/06/28 PHP
解决PHP使用CURL发送GET请求时传递参数的问题
2019/10/11 PHP
ASP.NET jQuery 实例14 在ASP.NET form中校验时间范围
2012/02/03 Javascript
javascript重写alert方法的实例代码
2013/03/29 Javascript
AngularJS基础学习笔记之指令
2015/05/10 Javascript
javascript搜索框效果实现方法
2015/05/14 Javascript
javascript电商网站抢购倒计时效果实现
2015/11/19 Javascript
js插件Jcrop自定义截取图片功能
2016/10/14 Javascript
jstl中判断list中是否包含某个值的简单方法
2016/10/14 Javascript
jQuery基于xml格式数据实现模糊查询及分页功能的方法
2016/12/25 Javascript
微信小程序商城项目之购物数量加减(3)
2017/04/17 Javascript
小程序登录之支付宝授权的实现示例
2019/12/13 Javascript
javascript操作向表格中动态加载数据
2020/08/27 Javascript
js 执行上下文和作用域的相关总结
2021/02/08 Javascript
python实现系统状态监测和故障转移实例方法
2013/11/18 Python
Python合并字符串的3种方法
2015/05/21 Python
python爬虫入门教程--快速理解HTTP协议(一)
2017/05/25 Python
mac下如何将python2.7改为python3
2018/07/13 Python
PyTorch搭建多项式回归模型(三)
2019/05/22 Python
python里dict变成list实例方法
2019/06/26 Python
Python 列表去重去除空字符的例子
2019/07/20 Python
Python原始套接字编程实例解析
2020/01/29 Python
使用TensorFlow直接获取处理MNIST数据方式
2020/02/10 Python
Python爬取豆瓣数据实现过程解析
2020/10/27 Python
纯css3使用vw和vh实现自适应的方法
2018/02/09 HTML / CSS
Get The Label中文官网:英国运动时尚购物平台
2017/04/19 全球购物
加拿大领先的冒险和户外零售商:Atmosphere
2017/12/19 全球购物
写出SQL四条最基本的数据操作语句(DML)
2012/12/12 面试题
深圳茁壮笔试题
2015/05/28 面试题
中秋联欢会主持词
2015/07/04 职场文书
2016优秀教师先进个人事迹材料
2016/02/25 职场文书
创业计划之特色精品店
2019/08/12 职场文书
导游词之桂林山水
2019/09/20 职场文书