drf框架接口文檔
REST framework可以自動幫助我們生成接口文檔。
接口文檔以網(wǎng)頁的方式呈現(xiàn)。
自動接口文檔能生成的是繼承自APIView及其子類的視圖。
一.安裝依賴
pip install coreapi
二.設(shè)置接口文檔訪問路徑
在總路由中添加接口文檔路徑。
文檔路由對應(yīng)的視圖配置為rest_framework.documentation.include_docs_urls,
參數(shù)title為接口文檔網(wǎng)站的標(biāo)題。
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('docs/', include_docs_urls(title='站點頁面標(biāo)題'))
]
推薦Python大牛在線分享技術(shù) 扣qun:855408893
領(lǐng)域:web開發(fā),爬蟲,數(shù)據(jù)分析,數(shù)據(jù)挖掘,人工智能
零基礎(chǔ)到項目實戰(zhàn),7天學(xué)習(xí)上手做項目
三.文檔描述說明定義位置
1) 單一方法的視圖,可直接使用類視圖的文檔字符串,如
class BookListView(generics.ListAPIView):
"""
返回所有圖書信息.
"""
2)包含多個方法的視圖,在類視圖的文檔字符串中,分開方法定義,如
class BookListCreateView(generics.ListCreateAPIView):
"""
get:
返回所有圖書信息.
post:
新建圖書.
"""
3)對于視圖集ViewSet,仍在類視圖的文檔字符串中封開定義,但是應(yīng)使用action名稱區(qū)分,如
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
"""
list:
返回圖書列表數(shù)據(jù)
retrieve:
返回圖書詳情數(shù)據(jù)
latest:
返回最新的圖書數(shù)據(jù)
read:
修改圖書的閱讀量
"""
四.訪問接口文檔網(wǎng)頁
有兩點要說明
1) 視圖集ViewSet中的retrieve名稱,在接口文檔網(wǎng)站中叫做read
2)參數(shù)的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': '閱讀量'
}
}