在我的项目的视图类中,我使用swagger_auto_schema
装饰器来定制swagger可能的响应。我的问题是:“这是一种将所有这些装饰器从我的基于类的视图移动到其他位置(如模块或python文件)的方法吗?".我问这个问题是因为swagger_auto_schema装饰器有时会占用我视图的大部分代码,并且阅读它们变得越来越困难。
例如:
class ArticleListCreateAPIView(ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def get_serializer_class(self):
if self.request.method == "GET":
return ArticleResponseSerializer
return super().get_serializer_class()
@swagger_auto_schema(
responses={
status.HTTP_201_CREATED: openapi.Response(
description="Successful article create",
schema=ArticleResponseSerializer,
),
status.HTTP_400_BAD_REQUEST: openapi.Response(
description="Data serialization failed. Incorrect data.",
schema=DetailResponseSerializer
),
status.HTTP_409_CONFLICT: openapi.Response(
description="Media-file is already bouned to some other model",
schema=DetailResponseSerializer
)
}
)
def post(self, request, *args,**kwargs):
...
也许我应该停止使用swagger_auto_schema并用其他结构来代替它?
1条答案
按热度按时间sqyvllje1#
我的解决方案是将responses parts、responses和swagger_auto_schema分别放在3个不同的地方。在我的项目根目录下,我创建了
utils
文件夹,在其中我以如下方式存储文件:在
response_templates.py
中有以下代码:因此,我可以在我的
swagger_auto_schema
装饰器中使用这些响应部分。下一步是在所有应用程序中创建responses
文件夹,那些需要在swagger.tree of responses文件夹中自定义响应的应用程序:在
image.py
中有以下代码:因此,作为上述重构的结果,我可以在
swagger_auto_schema
装饰器中使用上述响应。