Django中自動生成接口文檔的方法


1.簡介

REST framework可以自動幫助我們生成接口文檔,接口文檔以網頁的方式呈現。自動接口文檔能生成的是繼承自APIView及其子類的視圖。

2.下載依賴

rest-framewrok生成接口文檔需要coreapi庫的支持。

pip install coreapi

3.自動文檔生成方法

  • 在總路由中添加接口文檔路徑
from rest_framework.documentation import include_docs_urls

urlpatterns = [
    path('doc/', include_docs_urls(title='接口文檔的名稱'))
]
  • 配置文件進行配置(如果遇到報錯,需進行此步驟)
# 報錯: AttributeError: 'AutoSchema' object has no attribute 'get_link'
REST_FRAMEWORK = {
 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    # 新版drf schema_class默認用的是rest_framework.schemas.openapi.AutoSchema
}
  • 文檔描述說明的定義位置
    • 單一方法的視圖,可直接使用類視圖的文檔字符串
    • 包含多個方法的視圖,在類視圖的文檔字符串中,分開方法定義
    • 對於視圖集ViewSet,仍在類視圖的文檔字符串中封開定義,但是應使用action名稱區分
# 案例1
class BookListView(generics.ListAPIView):
    """
    返回所有圖書信息.
    """

# 案例2
class BookListCreateView(generics.ListCreateAPIView):
    """
    get:
    返回所有圖書信息.

    post:
    新建圖書.
    """

 # 案例3
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    """
    list:
    返回圖書列表數據

    retrieve:
    返回圖書詳情數據

    latest:
    返回最新的圖書數據

    read:
    修改圖書的閱讀量
    """

4.查看

瀏覽器訪問 127.0.0.1:8000/docs/,即可看到自動生成的接口文檔。

5.注意事項

1) 視圖集ViewSet中的retrieve名稱,在接口文檔網站中叫做read

2)參數的Description需要在模型類或序列化器類的字段中以help_text選項定義

# 案例1 
class Student(models.Model):
    ...
    age = models.IntegerField(default=0, verbose_name='年齡', help_text='年齡')
    ...

# 案例2
class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"
        extra_kwargs = {
            'age': {
                'required': True,
                'help_text': '年齡'
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM