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

2024-09-27 17:42:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试为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"]
}]

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

^{pr2}$

问题是openapi.json它由Swagger生成,没有securitydict,我不知道它是如何生成的。在

下面,展示了生成的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": {...}
}

有没有更好的方式来描述这个概念在我的招摇过市的设置? 或者你能描述一下这个过程是什么,以及它是如何工作的,以便生成openapi.json文件?在


Tags: 名称comjsonhttpreadexampletypeswagger
1条回答
网友
1楼 · 发布于 2024-09-27 17:42:48

如果有疑问,请检查代码。您可以看到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

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

^{pr2}$

然后您可以将此呈现器类用于视图。希望有帮助!在

相关问题 更多 >

    热门问题