版本信息:
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啥的