DRF中配置drf-yasg来使用swagger
简单使用,具体配置根据项目需求,安装drf-yasg并注册到app省略
在settings.py中做如下配置
# -----------------------------------------swagger配置-------------------------------------------
SWAGGER_SETTINGS = {
'LOGIN_URL': '/api-auth/login/',
'LOGOUT_URL': '/api-auth/logout/',
'PERSIST_AUTH': True,
'REFETCH_SCHEMA_WITH_AUTH': True,
'REFETCH_SCHEMA_ON_LOGOUT': True,
'DEFAULT_INFO': 'DjangoDrfTest.urls.swagger_info',#这里注意,更改DjangoDrfTest
'SECURITY_DEFINITIONS': {
'Basic': {
'type': 'basic'
},
'Bearer': {
'type': 'apiKey',
'name': 'authorization',
'in': 'header'
},
'Query': {
'type': 'apiKey',
'name': 'auth',
'in': 'query'
}
}
}
# -----------------------------------------------------------------------------------------------
在urls.py中加入如下代码
schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version='v1',
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@snippets.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=[permissions.AllowAny],
)
# 在urlpatterns中加入如下
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('api/article/', include('article.urls', namespace='article'))
]