django自動(dòng)添加接口文檔的實(shí)現(xiàn)
以下是使用 Django 和 django-rest-swagger(或替代方案 drf-yasg)生成 API 接口文檔的詳細(xì)指南。由于 django-rest-swagger 已停止維護(hù),推薦使用 drf-yasg(支持 Swagger 2.0 和 OpenAPI 3.0),但兩種方法均會(huì)說明:
一、方案選擇與安裝
1. 方案對比
| 庫名 | 維護(hù)狀態(tài) | 支持規(guī)范 | 功能特點(diǎn) |
|---|---|---|---|
| django-rest-swagger | 已棄用 | Swagger 2.0 | 舊項(xiàng)目兼容,文檔生成簡單 |
| drf-yasg | 活躍維護(hù) | OpenAPI 3.0 | 功能強(qiáng)大,支持更詳細(xì)的配置 |
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 的默認(rèn)權(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="項(xiàng)目接口文檔",
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 認(rèn)證
}
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. 認(rèn)證配置
• 場景: 需要登錄才能訪問 Swagger 文檔。
• 配置(在 settings.py 中):
SWAGGER_SETTINGS = {
'LOGIN_URL': '/admin/login/', # 登錄地址
'LOGOUT_URL': '/admin/logout/',
'USE_SESSION_AUTH': True,
}
3. 自定義文檔樣式
• 方法: 覆蓋默認(rèn)模板或使用 drf-yasg 的擴(kuò)展參數(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,功能更強(qiáng)大且維護(hù)活躍。
核心步驟:
- 安裝庫并配置
settings.py和urls.py。 - 通過裝飾器或注釋為視圖添加接口描述。
- 訪問
/swagger/查看文檔。
• 注意事項(xiàng):
• 確保視圖繼承自 DRF 的基類(如APIView)。
• 若接口涉及認(rèn)證(如 JWT),需在文檔中配置安全策略。
到此這篇關(guān)于django自動(dòng)添加接口文檔的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)django自動(dòng)接口文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決使用PyCharm時(shí)無法啟動(dòng)控制臺(tái)的問題
今天小編就為大家分享一篇解決使用PyCharm時(shí)無法啟動(dòng)控制臺(tái)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python?泛型函數(shù)--singledispatch的使用解讀
這篇文章主要介紹了python?泛型函數(shù)--singledispatch的使用解讀,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Python實(shí)現(xiàn)PDF掃描件生成DOCX或EXCEL功能
這篇文章主要介紹了如何利用Python實(shí)現(xiàn)將PDF掃描件轉(zhuǎn)為DOCX或EXCEL文件格式功能,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考一下2022-03-03
Python在字典中獲取帶權(quán)重的隨機(jī)值實(shí)現(xiàn)方式
這篇文章主要介紹了Python在字典中獲取帶權(quán)重的隨機(jī)值,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11
Python導(dǎo)入引用其他文件的函數(shù)實(shí)戰(zhàn)案例(推薦!)
這篇文章主要給大家介紹了關(guān)于Python導(dǎo)入引用其他文件的函數(shù)的相關(guān)資料,文中通過代碼以及圖文介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01
python實(shí)現(xiàn)發(fā)送郵件及附件功能
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)發(fā)送郵件及附件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
Python使用pip安裝報(bào)錯(cuò):is not a supported wheel on this platform的解決
這篇文章主要介紹了Python使用pip安裝報(bào)錯(cuò):is not a supported wheel on this platform的解決方法,結(jié)合實(shí)例形式分析了在安裝版本正確的情況下pip安裝報(bào)錯(cuò)的原因與相應(yīng)的解決方法,需要的朋友可以參考下2018-01-01

