Django REST Swagger:如何在Swagger设置中使用安全部分?

时间:2017-01-20 09:45:02

标签: python django swagger django-swagger

我试图为SecurityDefinition构建Swagger设置,以便在openapi.json中获得以下结果:

"securityDefinitions": {
  "password": {
    "type": "oauth2",
    "tokenUrl": "http://example.com/oauth/token",
    "flow": "password",
    "scopes": {
      "write": "allows modifying resources",
      "read": "allows reading resources"
    }
  }
},
"security": [{
  "password": ["read", "write"]
}]

在我的settings.py中,我添加了以下招摇设置:

# Swagger settings
SWAGGER_SETTINGS = {
  "SECURITY_DEFINITIONS": {
    "password": {
        "type": "oauth2",
        "tokenUrl": "http://example.com/oauth/token",
        "flow": "password",
        "scopes": {
            "write": "allows modifying resources",
            "read": "allows reading resources"
        }
     }
  },
  "SECURITY": [{
    "password": ["read", "write"]
  }]
}

问题在于,在Swagger生成的openapi.json中没有security dict,我也不知道它是如何生成的。

下面,展示了生成的openapi.json:

{
   "info": {
       "title": "Example Service API",
       "version": ""
   },
   "host": "http://example.com",
   "swagger": "2.0",
   "securityDefinitions": {
       "password": {
           "type": "oauth2",
           "scopes": {
               "write": "allows modifying resources",
               "read": "allows reading resources"
           },
           "tokenUrl": "http://example.com/oauth/token",
           "flow": "password"
       }
   },
   "paths": {...}
}

有没有更好的方法在我的Swagger设置中描述这个概念? 或者你能描述一下这个过程以及它如何工作以生成openapi.json文件吗?

1 个答案:

答案 0 :(得分:4)

如有疑问,请检查代码。您可以看到OpenAPIRenderer here的定义:

class OpenAPIRenderer(BaseRenderer):
    media_type = 'application/openapi+json'
    charset = None
    format = 'openapi'

    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context['response'].status_code != status.HTTP_200_OK:
            return JSONRenderer().render(data)
        extra = self.get_customizations()

        return OpenAPICodec().encode(data, extra=extra)

    def get_customizations(self):
        """
        Adds settings, overrides, etc. to the specification.
        """
        data = {}
        if swagger_settings.SECURITY_DEFINITIONS:
            data['securityDefinitions'] = swagger_settings.SECURITY_DEFINITIONS

        return data

所以这样做的一种方法是子类化,例如:

class MyOpenAPIRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super().get_customizations()

        # your customizations
        data["security"] = swagger_settings.SECURITY

        return data

然后您可以将此渲染器类用于视图。希望它有所帮助!