我正在为我的 Django Rest API 文档使用 drf-yasg 包。默认情况下,它只显示一个名为“Payload”的请求示例,如下面的链接所示。 https://i.stack.imgur.com/1Pno2.jpg 我想添加更多请求样本,如下图所示。 https://i.stack.imgur.com/yy9tv.png
问问题
417 次
1 回答
1
如果您从SwaggerAutoSchema类重写方法get_operation ,则可以添加它。
from drf_yasg.inspectors import SwaggerAutoSchema
class CustomAutoSchema(SwaggerAutoSchema):
def get_operation(self, operation_keys=None):
operation_keys = operation_keys or self.operation_keys
consumes = self.get_consumes()
produces = self.get_produces()
body = self.get_request_body_parameters(consumes)
query = self.get_query_parameters()
parameters = body + query
parameters = filter_none(parameters)
parameters = self.add_manual_parameters(parameters)
operation_id = self.get_operation_id(operation_keys)
summary, description = self.get_summary_and_description()
security = self.get_security()
assert security is None or isinstance(security, list), "security must be a list of security requirement objects"
deprecated = self.is_deprecated()
tags = self.get_tags(operation_keys)
responses = self.get_responses()
return openapi.Operation(
operation_id=operation_id,
description=force_real_str(description),
summary=force_real_str(summary),
responses=responses,
parameters=parameters,
consumes=consumes,
produces=produces,
tags=tags,
security=security,
deprecated=deprecated,
**{'x-code-samples': self.overrides.get('code_examples')}
)
然后你可以在你的视图中使用这个模式
class MyViewSet(viewsets.ModelViewSet):
swagger_schema = CustomAutoSchema
并将装饰器添加到您的视图方法中:
@swagger_auto_schema(
code_examples=[
{
'lang': 'bash',
'source': 'curl -H "Authorization: Token YOUR-API-KEY" https://developers.typless.com/api/document-types/'
},
]
)
您可以在此博客上阅读更多内容。
于 2020-05-13T10:40:48.323 回答