Django接入drf_yasg2 API接口文档-完整操作(包含错误处理)
drf_yasg2的简介:
drf-yasg是Django RestFramework的一个扩展,使⽤drf_yasg2下载⾃动⽣成的api⽂档的json或yaml⽂件配置项。
drf_yasg2的安装:
pip install drf-yasg2
drf_yasg2的settings.py 注册:
INSTALLED_APPS = [
......
'drf_yasg2', # 注册drf_yasg2 api接口drf_yasg2
]
drf_yasg2的主路由urls.py 注册:
# ######drf_yasg2的注册(开始)######
from rest_framework import permissions
from drf_yasg2.views import get_schema_view
from drf_yasg2 import openapi
schema_view = get_schema_view(
openapi.Info(
title="Python API",
default_version='v1',
description="Welcome to the world of Tweet",
),
public=True,
permission_classes=(permissions.AllowAny,),
)
# ######drf_yasg2的注册(结束)######
urlpatterns = [
# drf_yasg2的url注册
re_path(r'^doc(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
# drf_yasg2导出
path('doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # drf_yasg2美化UI
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), # drf_yasg2
]
drf_yasg2的测试:
启动测试
python manage.py runserver
drf_yasg2的错误处理:
drf-yasg2错误1:
ImportError: Could not import 'drf_yasg2.generators.OpenAPISchemaGenerator' for API setting 'DEFAULT_GENERATOR_CLASS'. ImportError: Module "drf_yasg2.generators" does not define a "OpenAPISchemaGenerator" attribute/class.
或者
drf-yasg2错误2:
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'
原因:DRF 3.14兼容问题
解决方法:降低DRF版本到3.13