【问题标题】:How to use the first line of the docstring as summary in drf-yasg如何在 drf-yasg 中使用文档字符串的第一行作为摘要
【发布时间】:2022-01-11 08:34:21
【问题描述】:
如何将get_list中的第一行注释设置为swagger文档中的摘要?
def get_list(self, request):
'''
I want to set this is summary
'''
configs = Config.objects.all()
serializer = self.serializer(configs, many=True)
return create_response(data=serializer.data)
【问题讨论】:
标签:
django-rest-framework
drf-yasg
【解决方案1】:
drf-yasg 现在应该默认以这种方式工作,但无论如何您都可以覆盖 SwaggerAutoSchema 以从模块文档字符串的第一行生成摘要。这是您可以使用的示例 sn-p:
class ECSwaggerAutoSchema(SwaggerAutoSchema):
"""EC modified Swagger schema used in settings"""
def __init__(self, view, path, method, components, request, overrides):
super(ECSwaggerAutoSchema, self).__init__(view, path, method, components, request, overrides)
def get_view_method_doc(self):
"""Returns the doc in view method if is available else None"""
try:
doc = getattr(self._sch.view, self._method).__doc__ # type: str or None
return doc if isinstance(doc, str) else None
except AttributeError:
return None
def get_summary(self):
"""Return a summary description for this operation.
If `operation_summary` is available will override the first line of the docstring.
:return: the summary
:rtype: str or None
"""
doc = self.get_description()
first_string_line = doc.split(sep='\n')[0] if doc else None
operation_summary = self.overrides.get('operation_summary', None)
return operation_summary if operation_summary else first_string_line