淺談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 SchemaGenerator from rest_framework.schemas.coreapi import LinkNode,insert_into from rest_framework.renderers import * from rest_framework_swagger import renderers from rest_framework.response import Response from rest_framework.decorators import APIView from rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnly from django.http import JsonResponse class 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,request) path = self.coerce_path(path,view) paths.append(path) view_endpoints.append((path,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,view in view_endpoints: if not self.has_view_permissions(path,view): continue link = view.schema.get_link(path,base_url=self.url) # 新增下面這一行方便在views編寫過程中自定義引數. link._fields += self.get_core_fields(view) subpath = path[len(prefix):] keys = self.get_keys(subpath,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 admin from rest_framework import routers from django.conf.urls import url,include # 下面是剛才自定義的schema from app.schema_view import SwaggerSchemaView # 自定義介面 from app.recommend import CustomView router = 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以及自定義引數問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。