当前位置: 首页 > 工具软件 > Django Silk > 使用案例 >

Django | Django-rest-swagger 使用手册

陈渊
2023-12-01

1. 安装 django-rest-swagger

pip install django-rest-swagger

2. setting.py 文件中添加

INSTALLED_APPS = [
    ...
    'rest_framework_swagger',
    ...
]

3.urls.py 文件中添加

写法一

from rest_framework_swagger.views import get_swagger_view
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer

schema_view = get_schema_view(
    title='API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer], public=True,
    authentication_classes=(),
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    ...
    path('doc', schema_view),
    ...
]

写法二

from rest_framework_swagger.views import get_swagger_view
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer

schema_view = get_swagger_view(title='API')

urlpatterns = [
    ...
    path('doc', schema_view),
    ...
]

4. setting.py 文件中添加

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
      #  'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            # 添加'libraries'内容解决报错:'staticfiles' is not a registered tag library.
            'libraries': { # Adding this section should work around the issue.
                'staticfiles' : 'django.templatetags.static',
            },
        },
    },
]
 类似资料: