django-rest-framework 自定义swagger过程详解


Posted in Python onJuly 18, 2019

前言

之前的文章编写了一个返回json的例子,直接用浏览器进行get请求虽然成功了, 但是接口文档的样式很难看, 不好用. 而且提示没有访问权限.

我们一般都希望能够直接在接口文档中进行请求, 以测试接口, 本篇文章中会给出一个自定义swagger(openapi)的例子. 使接口文档变得美观可用, 可以填写参数, 可以进行请求以观察数据格式, 测试接口是否可用.

环境

workon python35
pip list
chardet (3.0.4)
coreapi (2.3.3)
coreschema (0.0.4)
Django (1.11.6)
django-rest-swagger (2.1.2)
django-simple-serializer (2.0.7)
djangorestframework (3.7.1)
future (0.16.0)
idna (2.6)
itypes (1.1.0)
Jinja2 (2.9.6)
MarkupSafe (1.0)
openapi-codec (1.3.2)
pip (9.0.1)
pytz (2017.2)
requests (2.18.4)
setuptools (36.6.0)
simplejson (3.11.1)
uritemplate (3.0.0)
urllib3 (1.22)
wheel (0.30.0)

阿里云的源中 最新版的django-rest-frmework版本为3.7.1

3.6 与 3.7的结构稍有不同. 我之前用3.6, 但是以下对swagger的修改以3.7.1版本为基准. 理解原理之后不同版本只需要稍作修改即可.

第一步修改配置

进入settings.py 文件, 确保INSTALLED_APPS中包含rest_framework

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'rest_framework',
  'rest_framework_swagger',
  'mytest',
]

我们导入了三个框架

  • rest_framework
  • rest_framework_swagger
  • mytest (之前的文章中编写简单接口的app)

然后在settings.py 文件中添加以下代码

REST_FRAMEWORK = {
  # 下面这一行表示接口文档的访问权限, AllowAny不做权限限制.
  'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
  # 'PAGE_SIZE': 10,
  'PAGINATE_BY':10,
}


SWAGGER_SETTINGS = {
  # 基础样式
  'SECURITY_DEFINITIONS': {
    "basic":{
      'type': 'basic'
    }
  },
  # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的.
  'LOGIN_URL': 'rest_framework:login',
  'LOGOUT_URL': 'rest_framework:logout',
  # 'DOC_EXPANSION': None,
  # 'SHOW_REQUEST_HEADERS':True,
  # 'USE_SESSION_AUTH': True,
  # 'DOC_EXPANSION': 'list',
  # 接口文档中方法列表以首字母升序排列
  'APIS_SORTER': 'alpha',
  # 如果支持json提交, 则接口文档中包含json输入框
  'JSON_EDITOR': True,
  # 方法列表字母排序
  'OPERATIONS_SORTER': 'alpha',
  'VALIDATOR_URL': None,
}

第二步编写自定义的swagger接口文档页面.

思路:

之前urls.py中的接口文档页面来自这里

from rest_framework.schemas import get_schema_view

查看源码, 继承schema, 返回schema的子类即可.

接下来编写自己的schema

from rest_framework.permissions import AllowAny
from rest_framework.schemas import SchemaGenerator
from rest_framework.schemas.generators import LinkNode, insert_into
from rest_framework.renderers import *
from rest_framework_swagger import renderers
from rest_framework.response import Response

# from rest_framework.schemas import SchemaGenerator
class MySchemaGenerator(SchemaGenerator):

  def get_links(self, request=None):
    # from rest_framework.schemas.generators import LinkNode,
    links = LinkNode()

    paths = []
    view_endpoints = []
    for path, method, callback in self.endpoints:
      view = self.create_view(callback, method, request)
      path = self.coerce_path(path, method, view)
      paths.append(path)
      view_endpoints.append((path, method, view))

    # Only generate the path prefix for paths that will be included
    if not paths:
      return None
    prefix = self.determine_path_prefix(paths)

    for path, method, view in view_endpoints:
      if not self.has_view_permissions(path, method, view):
        continue
      link = view.schema.get_link(path, method, base_url=self.url)
      # 添加下面这一行方便在views编写过程中自定义参数.
      link._fields += self.get_core_fields(view)

      subpath = path[len(prefix):]
      keys = self.get_keys(subpath, method, view)

      # from rest_framework.schemas.generators import LinkNode, insert_into
      insert_into(links, keys, link)

    return links

  # 从类中取出我们自定义的参数, 交给swagger 以生成接口文档.
  def get_core_fields(self, view):
    return getattr(view, 'coreapi_fields', ())


class SwaggerSchemaView(APIView):
  _ignore_model_permissions = True
  exclude_from_schema = True

  # from rest_framework.permissions import AllowAny
  permission_classes = [AllowAny]
  # from rest_framework_swagger import renderers
  # from rest_framework.renderers import *
  renderer_classes = [
    CoreJSONRenderer,
    renderers.OpenAPIRenderer,
    renderers.SwaggerUIRenderer
  ]

  def get(self, request):
    generator = MySchemaGenerator(title='xxxxx',
                   description='''xxxxx''')

    schema = generator.get_schema(request=request)

    # from rest_framework.response import Response
    return Response(schema)

上面的代码中我加了注释, 写出了需要用到的一些方法, 参数, 类 都是从哪里import进来的.

上面的代码自定义了一个swagger页面, 加入了自定义参数的方法, 设置了访问权限(AllowAny), 添加了title和description,
原理, 其实就是继承父类, 重写方法以覆盖父类中的方法, 修改子类中overwrite的方法以添加我们想要的内容.

上面的代码其实写在哪里都可以, 找得到就行,我一般写在views.py 文件中和其他接口放在一起, 毕竟 http://xxxxx/docs/ 和/api/getjson 这样的接口一样都返回一个视图.

最后一步

修改urls.py文件, 把接口放出去.

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.schemas import get_schema_view
from mytest.views import ReturnJson
import mytest
# 下面是刚才自定义的schema
from mytest.views import SwaggerSchemaView

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
  url(r'^docs/', SwaggerSchemaView.as_view(), name='apiDocs'),
  url(r'^api/getjson', ReturnJson.as_view()),
]

注意上面我们添加了两个接口.

api-auth/和docs/

还记得配置文件中的他们吗

'LOGIN_URL': 'rest_framework:login',
'LOGOUT_URL': 'rest_framework:logout',

api-auth/就是为他俩准备的. 因为有时我们需要让接口文档登录之后才能够被看到..

最后运行项目看到

django-rest-framework 自定义swagger过程详解

剩下的问题

我们的第一个接口没有参数. 向接口文档的getjson接口添加一个参数.

修改 getjson接口对应的views.py文件中的类.ReturnJson类.

添加以下代码

def DocParam(name="default", location="query",
       required=True, description=None, type="string",
       *args, **kwargs):
  return coreapi.Field(name=name, location=location,
             required=required, description=description,
             type=type)


class ReturnJson(APIView):

  coreapi_fields=(
    DocParam("token"),
  )

  def get(self, request, *args, **kwargs):
    return JsonResponse("Hello world!!!!!!!!++++++中文测试")

这是所有的import

from django.shortcuts import render
from rest_framework.views import APIView
from dss.Serializer import serializer
from django.http import HttpResponse, HttpRequest
from rest_framework.permissions import AllowAny
from rest_framework.schemas import SchemaGenerator
from rest_framework.schemas.generators import LinkNode, insert_into
from rest_framework.renderers import *
from rest_framework_swagger import renderers
from rest_framework.response import Response
# from rest_framework.schemas import *

我也忘了. coreapi.Field是从哪里import的了....

以上代码为 getjson接口添加了token参数.

最终效果.

django-rest-framework 自定义swagger过程详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用win32com在百度空间插入html元素示例
Feb 20 Python
深入理解Python中装饰器的用法
Jun 28 Python
python 根据pid杀死相应进程的方法
Jan 16 Python
基于Python函数的作用域规则和闭包(详解)
Nov 29 Python
基于并发服务器几种实现方法(总结)
Dec 29 Python
Python处理文本换行符实例代码
Feb 03 Python
解决pycharm回车之后不能换行或不能缩进的问题
Jan 16 Python
使用python实现抓取腾讯视频所有电影的爬虫
Apr 15 Python
Python Django简单实现session登录注销过程详解
Aug 06 Python
使用Python的Turtle绘制哆啦A梦实例
Nov 21 Python
python time()的实例用法
Nov 03 Python
用Python提取PDF表格的方法
Apr 11 Python
django框架使用方法详解
Jul 18 #Python
Ubuntu+python将nii图像保存成png格式
Jul 18 #Python
python实现批量nii文件转换为png图像
Jul 18 #Python
django 捕获异常和日志系统过程详解
Jul 18 #Python
Django实现发送邮件功能
Jul 18 #Python
使用django的ORM框架按月统计近一年内的数据方法
Jul 18 #Python
Django框架之登录后自定义跳转页面的实现方法
Jul 18 #Python
You might like
WINDOWS服务器安装多套PHP的另类解决方案
2006/10/09 PHP
PHP中比较时间大小实例
2014/08/21 PHP
PHP自定义函数格式化json数据示例
2016/09/14 PHP
利用JQuery+EasyDrag 实现弹出可拖动的Div,同时向Div传值,然后返回Div选中的值
2009/10/24 Javascript
javascript学习(二)javascript常见问题总结
2013/01/02 Javascript
jquery获取子节点和父节点的示例代码
2013/09/10 Javascript
完美解决IE低版本不支持call与apply的问题
2013/12/05 Javascript
JS简单操作select和dropdownlist实例
2014/11/26 Javascript
Nodejs关于gzip/deflate压缩详解
2015/03/04 NodeJs
nodejs通过phantomjs实现下载网页
2015/05/04 NodeJs
js仿黑客帝国字母掉落效果代码分享
2020/11/08 Javascript
js文本框走动跑马灯效果代码分享
2015/08/25 Javascript
js实现表单多按钮提交action的处理方法
2015/10/24 Javascript
JavaScript中数组添加值和访问值常见问题
2016/02/06 Javascript
老生常谈javascript的类型转换
2016/10/12 Javascript
详解在vue-cli项目中安装node-sass
2017/06/21 Javascript
electron + vue项目实现打印小票功能及实现代码
2018/11/25 Javascript
JavaScript函数的特性与应用实践深入详解
2018/12/30 Javascript
[04:09]2014DOTA2国际邀请赛Ti西雅图 历届冠军相继出局 BBC综述今日比赛
2014/07/20 DOTA
[01:00:12]2018DOTA2亚洲邀请赛 4.7 淘汰赛 VP vs LGD 第一场
2018/04/09 DOTA
使用Python设置tmpfs来加速项目的教程
2015/04/17 Python
python中关于for循环的碎碎念
2017/06/30 Python
利用Python进行图像的加法,图像混合(附代码)
2019/07/14 Python
用python实现英文字母和相应序数转换的方法
2019/09/18 Python
Python解释器以及PyCharm的安装教程图文详解
2020/02/26 Python
英国知名小木屋定制网站:Tiger Sheds
2020/03/06 全球购物
大学生毕业求职找工作的自我评价
2013/09/29 职场文书
函授毕业个人自我评价
2014/02/20 职场文书
招聘专员岗位职责
2014/03/07 职场文书
公司年会搞笑主持词
2014/03/24 职场文书
中医学专业自荐信范文
2014/04/01 职场文书
媒矿安全生产承诺书
2014/05/23 职场文书
语文教师求职信范文
2015/03/20 职场文书
刑事撤诉申请书
2015/05/18 职场文书
fastdfs+nginx集群搭建的实现
2021/03/31 Servers
Kubernetes部署实例并配置Deployment、网络映射、副本集
2022/04/01 Servers