REST framework可以自動幫助我們生成介面檔案,
介面檔案以網頁的方式呈現,
自動介面檔案能生成的是繼承自APIView及其子類的視圖,
1. 安裝依賴
REST framewrok生成介面檔案需要coreapi庫的支持,
pip install coreapi
2. 設定介面檔案訪問路徑
在總路由中添加介面檔案路徑,
檔案路由對應的視圖配置為rest_framework.documentation.include_docs_urls,
引數title為介面檔案網站的標題,
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API title'))
]
3. 檔案描述說明的定義位置
1) 單一方法的視圖,可直接使用類視圖的檔案字串,如
class BookListView(generics.ListAPIView):
"""
回傳所有圖書資訊.
"""
2)包含多個方法的視圖,在類視圖的檔案字串中,分開方法定義,如
class BookListCreateView(generics.ListCreateAPIView):
"""
get:
回傳所有圖書資訊.
post:
新建圖書.
"""
3)對于視圖集ViewSet,仍在類視圖的檔案字串中分開定義,但是應使用action名稱區分,如
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
"""
list:
回傳圖書串列資料
retrieve:
回傳圖書詳情資料
latest:
回傳最新的圖書資料
read:
修改圖書的閱讀量
"""
4. 訪問介面檔案網頁
瀏覽器訪問 127.0.0.1:8000/docs/,即可看到自動生成的介面檔案,

兩點說明:
1) 視圖集ViewSet中的retrieve名稱,在介面檔案網站中叫做read
2)引數的Description需要在模型類或序列化器類的欄位中以help_text選項定義,如:
class BookInfo(models.Model):
...
bread = models.IntegerField(default=0, verbose_name='閱讀量', help_text='閱讀量')
...
或
class BookReadSerializer(serializers.ModelSerializer):
class Meta:
model = BookInfo
fields = ('bread', )
extra_kwargs = {
'bread': {
'required': True,
'help_text': '閱讀量'
}
}
第二種介面檔案
drf-yasg
# 安裝
pip install drf-yasg
# 添加到
INSTALLED_APPS = [
'drf_yasg',
]
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="介面檔案平臺", # 必傳
default_version='v1', # 必傳
description="檔案描述",
terms_of_service='',
contact=openapi.Contact(email="[email protected]"),
license=openapi.License(name="BSD LICENSE")
),
public=True,
# permission_classes=(permissions.) # 權限類
)
urlpatterns += [
# re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0)),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]


轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/229770.html
標籤:Python
上一篇:圖解Linux網路包接收程序
