django-rest-swagger的优化使用
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,欢迎指出