欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-02 09:52:16
如下所示: requirements.txt django==1.10.5 djangorestframework==3.5.3 django-re...

如下所示:

requirements.txt
django==1.10.5

djangorestframework==3.5.3

django-rest-swagger==2.1.1

参考英文文档:

使用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的优化使用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。