版本信息:
python==3.6 django==1.11.17 djangorestframework==3.11.0
1.安装 pip install django-rest-swagger
版本信息:
django-rest-wagger==2.2.0
2.配置
2.1.在settings.py文件中以下位置添加模块名称
INSTALLED_APPS = [ 'rest_framework_swagger', ]
2.2.在settings.py文件中添加以下配置:增添'会话登录'跳转
SWAGGER_SETTINGS = { # 基础样式 'SECURITY_DEFINITIONS': { "basic":{ 'type': 'basic' } }, # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的. 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', # 'DOC_EXPANSION': None, # 'SHOW_REQUEST_HEADERS':True, # 'USE_SESSION_AUTH': True, # 'DOC_EXPANSION': 'list', # 接口文档中方法列表以首字母升序排列 'APIS_SORTER': 'alpha', # 如果支持json提交, 则接口文档中包含json输入框 'JSON_EDITOR': True, # 方法列表字母排序 'OPERATIONS_SORTER': 'alpha', 'VALIDATOR_URL': None, }
2.3.在settings.py同级目录下的urls对应位置添加以下内容
from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer schema_view=get_schema_view(title='API_Doc',renderer_classes=[OpenAPIRenderer,SwaggerUIRenderer]) urlpatterns = [ url(r'^docs/', schema_view, name='docs'), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
完成以上配置启动django:
python manage.py runserver
浏览器访问链接:http://127.0.0.1:8000/docs/
出现以下错误:
Internal Server Error: /docs/ Traceback (most recent call last): File "/home/hacker/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/hacker/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hacker/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/home/hacker/.local/lib/python3.6/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/home/hacker/.local/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/renderers.py", line 54, in render self.set_context(data, renderer_context) File "/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/renderers.py", line 70, in set_context renderer_context=renderer_context File "/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/renderers.py", line 34, in render return OpenAPICodec().encode(data, **options) File "/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/renderers.py", line 16, in encode raise TypeError('Expected a `coreapi.Document` instance') TypeError: Expected a `coreapi.Document` instance
解决
# 将djangorestframework 版本降低为3.9 pip install djangorestframework==3.9.2 -i https://pypi.douban.com/simple/
启动,ok
听说:django高版本的swagger已经不被维护,替换为drf啥的