【Django-DRF框架】生成各种API接口文档

方式一:

1、安装

pipenv install coreapi
pipenv install Pygments
pipenv install Markdown

2、配置

REST_FRAMEWORK = {
    
    
   ......

    #指定用于支持coreapi的Schema
    'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema'
}

3、在全局路由条目中,定义路由条目

from rest_framework.documentation import include_docs_urls

path('docs/',include_docs_urls(title='接口测试平台API文档',description='这个是接口平台的文档')),

4、访问接口文档

http://192.168.17.129:8000/docs/
在这里插入图片描述

方式二:

使用drf-yasg

1、安装

pip install drf-yasg

2、添加到settings.py文件中的INSTALLED_APPS(子应用)中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'drf_yasg',         #生成接口文档子应用
    'projects',
    'interfaces',
    'django_filters'    #DRF过滤器子应用

]

3、配置,到全局路由文件中

from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework.documentation import include_docs_urls

from projects import views

# drf_yasg 从这里开始
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="Tweet API",
        default_version='v1',
        description="Welcome to the world of Tweet",
        terms_of_service="http://api.zhilong.site",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),  # 权限类
)

4、指定路由条目

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('',include('projects.urls')),

    path('docs/',include_docs_urls(title='接口测试平台API文档',description='这个是接口平台的文档')),

    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),  # <-- 这里
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),  # <-- 这里
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),  # <-- 这里

]

5、访问接口文档

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/YZL40514131/article/details/124823765