gpt4 book ai didi

python - Django REST 摇摇欲坠 : How to use security section in Swagger settings?

转载 作者:太空狗 更新时间:2023-10-30 00:05:30 27 4
gpt4 key购买 nike

我正在尝试为 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 设置:

# 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 字典,我不知道它是如何生成的。

下面展示了生成的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 文件的过程是什么以及它是如何工作的吗?

最佳答案

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

然后您可以将此渲染器类用于您的 View 。希望对您有所帮助!

关于python - Django REST 摇摇欲坠 : How to use security section in Swagger settings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41760465/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com