淺談django框架集成swagger以及自定義參數(shù)問題
介紹
我們在實際的開發(fā)工作中需要將django框架與swagger進行集成,用于生成API文檔。網(wǎng)上也有一些關(guān)于django集成swagger的例子,但由于每個項目使用的依賴版本不一樣,因此可能有些例子并不適合我們。我也是在實際集成過程中遇到了一些問題,例如如何自定義參數(shù)等問題,最終成功集成,并將結(jié)果分享給大家。
開發(fā)版本
我開發(fā)使用的依賴版本,我所使用的都是截止發(fā)稿日期為止最新的版本:
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、設(shè)置DEFAULT_SCHEMA_CLASS,此處不設(shè)置后續(xù)會報錯。
REST_FRAMEWORK = { ...... 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema', ...... }
在app下面創(chuàng)建schema_view.py
在此文件中,我們要繼承coreapi中的SchemaGenerator類,并重寫get_links方法,重寫的目的就是實現(xiàn)我們自定義參數(shù),并且能在頁面上展示。此處直接復制過去使用即可。
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, 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編寫過程中自定義參數(shù). 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 # 從類中取出我們自定義的參數(shù), 交給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] # 此處涉及最終展示頁面權(quán)限問題,如果不需要認證,則使用AllowAny,這里需要權(quán)限認證,因此使用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)
實際應(yīng)用
在你的應(yīng)用中定義一個接口,并發(fā)布。我這里使用一個測試接口進行驗證。
注意
1、所有的接口必須采用calss的方式定義,因為要繼承APIView。
2、class下方的注釋post,是用來描述post方法的作用,會在頁面上進行展示。
3、coreapi_fields 中定義的屬性name是參數(shù)名稱,location是傳值方式,我這里一個采用query查詢,一個采用header,因為我們進行身份認證,必須將token放在header中,如果你沒有,去掉就好了,這里的參數(shù)根據(jù)你實際項目需要進行定義。
4、最后定義post方法,也可以是get、put等等,根據(jù)實際情況定義。
# 這里是之前在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、接收參數(shù)這塊一定要注意,我定義了一個公用的方法,這里不做過多闡述,如實際過程遇到應(yīng)用接口與swagger調(diào)用接口的傳值問題,可參考如下代碼。
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/
總結(jié)
以上這篇淺談django框架集成swagger以及自定義參數(shù)問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于django 數(shù)據(jù)庫遷移(migrate)應(yīng)該知道的一些事
今天小編就為大家分享一篇關(guān)于django 數(shù)據(jù)庫遷移(migrate)應(yīng)該知道的一些事,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05基于Python實現(xiàn)批量讀取大量nc格式文件并導出全部時間信息
這篇文章主要為大家詳細介紹了如何基于Python語言,逐一讀取大量.nc格式的多時相柵格文件并導出其中所具有的全部時間信息的方法,需要的可以參考下2024-01-01Python3.9最新版下載與安裝圖文教程詳解(Windows系統(tǒng)為例)
這篇文章主要介紹了Python3.9最新版下載與安裝圖文教程詳解,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11