介面檔案
介面撰寫已經寫完了,需要撰寫介面檔案,給前端的人使用
-請求地址
-請求方式
-支持的編碼格式
-請求引數(get,post引數)
-回傳格式示例
在公司的寫法
1)直接使用word或者md寫
2)使用介面檔案平臺,在介面檔案平臺錄入(Yapi(百度開源的自己搭建),第三方平臺(收費),自己開發介面檔案平臺)
-https://www.showdoc.com.cn/item/index
- 不想花錢,沒有能力開發,就使用開源的YAPI, https://zhuanlan.zhihu.com/p/366025001
3)專案自動生成:swagger,coreapi
-1 下載:pip3 install coreapi
-2 路由中配置:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
path('docs/', include_docs_urls(title='站點頁面標題'))
]
-3 在視圖類中加注釋
-4 在組態檔中配置
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
自動生成介面檔案
REST framework可以自動幫助我們生成介面檔案,
介面檔案以網頁的方式呈現,
自動介面檔案能生成的是繼承自APIView及其子類的視圖
安裝依賴
REST framewrok生成介面檔案需要coreapi庫的支持,
pip install coreapi
設定介面檔案
在總路由中添加介面檔案路徑,
檔案路由對應的視圖配置為rest_framework.documentation.include_docs_urls,
引數title為介面檔案網站的標題,
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('docs/', include_docs_urls(title='站點頁面標題'))
]
檔案描述說明的定義位置
單一方法的視圖,可以直接使用類視圖的檔案字串
class BookListView(generics.ListAPIView):
"""
回傳所有圖書資訊.
"""
包含多個方法的視圖,在類視圖的檔案字串中,分開方法定義
class BookListCreateView(generics.ListCreateAPIView):
"""
get:
回傳所有圖書資訊.
post:
新建圖書.
"""
對于視圖集ViewSet,仍在類視圖的檔案字串中封開定義,但是應使用action名稱區分
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
"""
list:
回傳圖書串列資料
retrieve:
回傳圖書詳情資料
latest:
回傳最新的圖書資料
read:
修改圖書的閱讀量
"""
訪問介面檔案網頁
瀏覽器訪問 127.0.0.1:8000/docs/,即可看到自動生成的介面檔案,
注意要點
1) 視圖集ViewSet中的retrieve名稱,在介面檔案網站中叫做read
2)引數的Description需要在模型類或序列化器類的欄位中以help_text選項定義
class Student(models.Model):
...
age = models.IntegerField(default=0, verbose_name='年齡', help_text='年齡')
...
或
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = "__all__"
extra_kwargs = {
'age': {
'required': True,
'help_text': '年齡'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518837.html
標籤:Python
