验证Swagger API文档(drf-yasg)

时间:2018-02-08 14:25:25

标签: django django-rest-framework drf-yasg

我已设置DRF-YASG,但无法弄清楚如何配置它以显示需要身份验证的视图。

以下是配置。

  schema_view = get_schema_view(
      openapi.Info(
        title="Swagger Doc",
        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"),
      ),
      validators=['flex', 'ssv'],
      permission_classes=(permissions.AllowAny,),  # If I change the permission it throws an exception. See below
      public=False,
      patterns=public_apis,
  )

public_apis是我希望他们在自己进行身份验证后看到的API。

使用上述配置,它不会显示单个API。它仅显示Authorize按钮和显示No operations defined in spec!的文字。但是,如果我将public=False更改为public=True,则会显示所有API。

PS:之前我使用的是Django Rest Swagger,我只能在提供JWT令牌后才能将其配置为显示API。

我正在使用JWT进行身份验证。

权限更改例外:

另一个问题是,如果我将上述权限更改为DRF Permission类,则呈现将失败并显示以下错误:

  Internal Server Error: /swagger/
  Traceback (most recent call last):
    File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
      response = get_response(request)
    File "/usr/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 "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response
      response = response.render()
    File "/usr/local/lib/python3.6/site-packages/django/template/response.py", line 107, in render
      self.content = self.rendered_content
    File "/usr/local/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content
      ret = renderer.render(self.data, accepted_media_type, context)
    File "/usr/local/lib/python3.6/site-packages/drf_yasg/renderers.py", line 54, in render
      self.set_context(renderer_context, swagger)
    File "/usr/local/lib/python3.6/site-packages/drf_yasg/renderers.py", line 62, in set_context
      renderer_context['title'] = swagger.info.title
  AttributeError: 'dict' object has no attribute 'info'
  Internal Server Error: /swagger/

我已尝试将其更改为permmissions.IsAuthenticated和我自己的自定义权限类,但它们都会因同样的错误而失败。

1 个答案:

答案 0 :(得分:0)

原来问题是我在DRF的rest_framework.authentication.SessionAuthentication中遗失了DEFAULT_AUTHENTICATION_CLASSES

因此,通过Django Admin登录视图登录后发送的请求对象没有用户,因此所有权限类都保持失败,然后会导致上述错误。

所以在添加之后,drf-yasg显示了它的所有荣耀。

<强>错误:

当发生这种情况时它抛出的错误虽然被引发为bug。请参阅#issue58