淺談django框架集成swagger以及自定義參數問題
介紹
我們在實際的開發工作中需要將django框架與swagger進行集成,用于生成API文檔。網上也有一些關于django集成swagger的例子,但由于每個項目使用的依賴版本不一樣,因此可能有些例子并不適合我們。我也是在實際集成過程中遇到了一些問題,例如如何自定義參數等問題,最終成功集成,并將結果分享給大家。
開發版本
我開發使用的依賴版本,我所使用的都是截止發稿日期為止最新的版本:
Django 2.2.7
django-rest-swagger 2.2.0
djangorestframework 3.10.3
修改settings.py
1、項目引入rest_framework_swagger依賴
INSTALLED_APPS = [ ...... ’rest_framework_swagger’, ......]
2、設置DEFAULT_SCHEMA_CLASS,此處不設置后續會報錯。
REST_FRAMEWORK = { ...... ’DEFAULT_SCHEMA_CLASS’: ’rest_framework.schemas.AutoSchema’, ......}
在app下面創建schema_view.py
在此文件中,我們要繼承coreapi中的SchemaGenerator類,并重寫get_links方法,重寫的目的就是實現我們自定義參數,并且能在頁面上展示。此處直接復制過去使用即可。
from rest_framework.schemas import SchemaGeneratorfrom rest_framework.schemas.coreapi import LinkNode, insert_intofrom rest_framework.renderers import *from rest_framework_swagger import renderersfrom rest_framework.response import Responsefrom rest_framework.decorators import APIViewfrom rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnlyfrom django.http import JsonResponseclass MySchemaGenerator(SchemaGenerator): def get_links(self, request=None): 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 #permission_classes = [AllowAny] # 此處涉及最終展示頁面權限問題,如果不需要認證,則使用AllowAny,這里需要權限認證,因此使用IsAuthenticated permission_classes = [IsAuthenticated] # from rest_framework.renderers import * renderer_classes = [ CoreJSONRenderer, renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): # 此處的titile和description屬性是最終頁面最上端展示的標題和描述 generator = MySchemaGenerator(title=’API說明文檔’,description=’’’接口測試、說明文檔’’’) schema = generator.get_schema(request=request) # from rest_framework.response import Response return Response(schema)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)
實際應用
在你的應用中定義一個接口,并發布。我這里使用一個測試接口進行驗證。
注意
1、所有的接口必須采用calss的方式定義,因為要繼承APIView。
2、class下方的注釋post,是用來描述post方法的作用,會在頁面上進行展示。
3、coreapi_fields 中定義的屬性name是參數名稱,location是傳值方式,我這里一個采用query查詢,一個采用header,因為我們進行身份認證,必須將token放在header中,如果你沒有,去掉就好了,這里的參數根據你實際項目需要進行定義。
4、最后定義post方法,也可以是get、put等等,根據實際情況定義。
# 這里是之前在schema_view.py中定義好的通用方法,引入進來 from app.schema_view import DocParam’’’ 測試’’’class CustomView(APIView): ’’’ post: 測試測試測試 ’’’ coreapi_fields = ( DocParam(name='id',location=’query’,description=’測試接口’), DocParam(name='AUTHORIZATION', location=’header’, description=’token’), ) def post(self, request): print(request.query_params.get(’id’)); return JsonResponse({’message’:’成功!’})
5、接收參數這塊一定要注意,我定義了一個公用的方法,這里不做過多闡述,如實際過程遇到應用接口與swagger調用接口的傳值問題,可參考如下代碼。
def getparam(attr,request): obj = request.POST.get(attr); if obj is None: obj = request.query_params.get(attr); return obj;
修改url.py
針對上一步中定義的測試接口,我們做如下配置。
from django.contrib import adminfrom rest_framework import routersfrom django.conf.urls import url,include# 下面是剛才自定義的schemafrom app.schema_view import SwaggerSchemaView# 自定義接口from app.recommend import CustomViewrouter = routers.DefaultRouter()urlpatterns = [ # swagger接口文檔路由 url(r'^docs/$', SwaggerSchemaView.as_view()), url(r’^admin/’, admin.site.urls), url(r’^’, include(router.urls)), # drf登錄 url(r’^api-auth/’, include(’rest_framework.urls’, namespace=’rest_framework’)) # 測試接口 url(r’^test1’, CustomView.as_view(), name=’test1’),]
效果展示
訪問地址:http://localhost:8001/docs/
總結
以上這篇淺談django框架集成swagger以及自定義參數問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: