我正在使用 DRF 开发一个 Django 项目。我也用过drf-yasg用于文档目的。
长话短说:我正在使用基于类的 View ,并且我有一些非常相似的 API,我决定创建一个父类(super class)并在其中实现 API 的公共(public)部分!为了更清楚:
class MySuperApiView(APIView):
permission_classes = [<some permission classes>]
def uncommon(self):
pass # to be override in subclasses
@swagger_auto_schema(request_body=request_body, responses=api_responses)
def post(self, *args, **kwargs):
# do some common stuff here
self.uncommon()
# do some other common stuff here
我只是重写子类中的uncommon
方法:
class SomeCustomApi(MySuperApiView):
def uncommon(self):
# do specific things here
它工作正常,但我有一个小问题:每个 Api 都有自己的 api_responses
,它是在父类(super class)的 swagger_auto_schema
装饰器中初始化的!而且无法更改!
针对这种情况,您有什么建议?我真的很想做 OOP 并遵守 DRY 原则。
最佳答案
我终于找到了在 Django 中做这样的事情的最佳方法! (所以是的,我不知道如何在其他框架或语言中处理这样的问题!)
我使用名为 method_decorator
的类装饰器将 swagger_auto_schema 装饰器移动到子类。所以首先我必须导入这个方法:
from django.utils.decorators import method_decorator
然后我像这样更改了父类(super class)和子类:
class MySuperApiView(APIView):
permission_classes = [<some permission classes>]
def uncommon(self):
pass # to be override in subclasses
# <I removed decorator from here!>
def post(self, *args, **kwargs):
# do some common stuff here
self.uncommon()
# do some other common stuff here
api_responses = # responses which belong to "SomeCustomApi"
@method_decorator(name='post',
decorator=swagger_auto_schema(request_body=request_body,
responses=api_responses))
class SomeCustomApi(MySuperApiView):
def uncommon(self):
# do specific things here
它工作得很好:)但是我更喜欢一个解决方案,在这个解决方案中我不必重复装饰器,而只需初始化 responses
参数。如果您在其他语言中遇到此类问题,并且您有其他语言的答案,请发布您的答案。
关于python - 如何处理类层次结构中的Python装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180272/