django-rest-swagger的優化使用方法
阿新 • • 發佈:2020-01-09
如下所示:
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的優化使用方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。