django自動添加接口文檔的實現(xiàn)
以下是使用 Django 和 django-rest-swagger(或替代方案 drf-yasg)生成 API 接口文檔的詳細指南。由于 django-rest-swagger
已停止維護,推薦使用 drf-yasg(支持 Swagger 2.0 和 OpenAPI 3.0),但兩種方法均會說明:
一、方案選擇與安裝
1. 方案對比
庫名 | 維護狀態(tài) | 支持規(guī)范 | 功能特點 |
---|---|---|---|
django-rest-swagger | 已棄用 | Swagger 2.0 | 舊項目兼容,文檔生成簡單 |
drf-yasg | 活躍維護 | OpenAPI 3.0 | 功能強大,支持更詳細的配置 |
2. 安裝推薦庫(drf-yasg)
# 安裝 drf-yasg(推薦) pip install drf-yasg # 或安裝舊版 django-rest-swagger(不推薦) # pip install django-rest-swagger==2.2.0
二、配置 drf-yasg 生成接口文檔(推薦)
1. 配置 settings.py
# settings.py INSTALLED_APPS = [ ... 'rest_framework', 'drf_yasg', # 添加 drf-yasg ] # 可選:配置 DRF 的默認權(quán)限(按需設(shè)置) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] }
2. 配置 URL 路由
# urls.py from django.urls import path, include from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi # 定義 Swagger 文檔視圖 schema_view = get_schema_view( openapi.Info( title="API 文檔", default_version='v1', description="項目接口文檔", terms_of_service="https://example.com/terms/", contact=openapi.Contact(email="contact@example.com"), license=openapi.License(name="MIT License"), ), public=True, permission_classes=(permissions.AllowAny,), # 控制文檔訪問權(quán)限 ) urlpatterns = [ # Swagger 文檔路由 path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='redoc'), # 其他 API 路由 path('api/', include('myapp.urls')), ]
3. 為視圖添加文檔注釋
在視圖(如 views.py
)中使用裝飾器或 YAML 注釋描述接口:
from drf_yasg.utils import swagger_auto_schema from rest_framework.views import APIView from rest_framework.response import Response class UserListView(APIView): @swagger_auto_schema( operation_description="獲取用戶列表", manual_parameters=[ openapi.Parameter( 'page', openapi.IN_QUERY, description="頁碼", type=openapi.TYPE_INTEGER ), ], responses={200: '成功獲取用戶列表'} ) def get(self, request): return Response({"users": []})
4. 訪問文檔
• Swagger UI: http://localhost:8000/swagger/
• ReDoc: http://localhost:8000/redoc/
三、使用舊版 django-rest-swagger(不推薦)
1. 配置 settings.py
# settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework_swagger', # 添加 django-rest-swagger ] # 配置 Swagger 設(shè)置 SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'USE_SESSION_AUTH': False, # 是否啟用 Django 的 Session 認證 }
2. 配置 URL 路由
# urls.py from django.urls import path from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer schema_view = get_schema_view( title="API 文檔", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer] ) urlpatterns = [ path('swagger/', schema_view, name='swagger'), path('api/', include('myapp.urls')), ]
3. 為視圖添加注釋
在視圖類或函數(shù)中使用文檔字符串(YAML 格式):
class UserListView(APIView): def get(self, request): """ 獲取用戶列表 --- parameters: - name: page in: query type: integer required: false description: 頁碼 responses: 200: description: 成功返回用戶列表 """ return Response({"users": []})
4. 訪問文檔
• 訪問 http://localhost:8000/swagger/
四、常見問題與優(yōu)化
1. 文檔不顯示接口
• 原因: 視圖未繼承 APIView
或未配置路由。
• 解決: 確保所有接口使用 DRF 的視圖類(如 APIView
, ViewSet
),并正確注冊到路由。
2. 認證配置
• 場景: 需要登錄才能訪問 Swagger 文檔。
• 配置(在 settings.py
中):
SWAGGER_SETTINGS = { 'LOGIN_URL': '/admin/login/', # 登錄地址 'LOGOUT_URL': '/admin/logout/', 'USE_SESSION_AUTH': True, }
3. 自定義文檔樣式
• 方法: 覆蓋默認模板或使用 drf-yasg
的擴展參數(shù):
schema_view = get_schema_view( ... patterns=[...], # 指定要包含的路由 generator_class='myapp.schemas.CustomSchemaGenerator', # 自定義生成器 )
4. 隱藏特定接口
• 使用 drf_yasg
:
@swagger_auto_schema(auto_schema=None) def my_view(request): ...
五、總結(jié)
推薦方案: 使用 drf-yasg,功能更強大且維護活躍。
核心步驟:
- 安裝庫并配置
settings.py
和urls.py
。 - 通過裝飾器或注釋為視圖添加接口描述。
- 訪問
/swagger/
查看文檔。
• 注意事項:
• 確保視圖繼承自 DRF 的基類(如APIView
)。
• 若接口涉及認證(如 JWT),需在文檔中配置安全策略。
到此這篇關(guān)于django自動添加接口文檔的實現(xiàn)的文章就介紹到這了,更多相關(guān)django自動接口文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python如何利用Har文件進行遍歷指定字典替換提交的數(shù)據(jù)詳解
這篇文章主要給大家介紹了關(guān)于Python如何利用Har文件進行遍歷指定字典替換提交的數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11python將excel轉(zhuǎn)換為csv的代碼方法總結(jié)
在本篇文章里小編給大家分享了關(guān)于python如何將excel轉(zhuǎn)換為csv的實例方法和代碼內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-07-07使用python調(diào)用zxing庫生成二維碼圖片詳解
本篇文章主要介紹了使用python調(diào)用zxing庫生成二維碼圖片,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01Python中plt.plot()、plt.scatter()和plt.legend函數(shù)的用法示例
今天想要用matplotlib中的plt函數(shù)繪制圖表,將多個數(shù)據(jù)曲線在一個圖表中進行呈現(xiàn),下面這篇文章主要給大家介紹了關(guān)于Python中plt.plot()、plt.scatter()和plt.legend函數(shù)用法的相關(guān)資料,需要的朋友可以參考下2022-03-03使用Python第三方庫xlrd讀取Excel中的數(shù)據(jù)的流程步驟
這篇文章主要給大家介紹了使用Python第三方庫xlrd讀取Excel中的數(shù)據(jù)的流程步驟,文中通過代碼示例給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-12-12