我有一个mixin,用于定义要在另一个类中覆盖的finalize_response()
方法:
class APILoggingMixin(object):
"""
Provides logging functionality by overriding finalize_response().
Intended to be mixed in with any rest_framework.views.APIView
"""
def finalize_response(self, request, response, *args, **kwargs):
logger.info('Some message.')
return super(APILoggingMixin, self).finalize_response(request, response, *args, **kwargs)
实现finalize_response()
方法的类。在同一模块中,定义了logger
全局变量:
import logging
logger = logging.getLogger(__name__)
class CategoryDetail(APILoggingMixin, generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a Category.
"""
model = Category
serializer_class = CategorySerializer
permission_classes = (permissions.IsAuthenticated,)
如何访问mixin中的logger
变量?
答案 0 :(得分:2)
意识到APILoggingMixin.finalize_response
需要self
CategoryDetail
实例,我们可以将记录器附加到CategoryDetail
class CategoryDetail(...):
logger = logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.logger.info('Some message.')
# Or through get_logger()
class CategoryDetail(...):
def get_logger(self):
return logger
class APILoggingMixin(object):
def finalize_response(self, ...):
self.get_logger().info('Some message.')
def get_logger(self):
raise NotImplementedError
# Or take advantage of the fact that `self.__module__` equals to `__name__` in the module of `CategoryDetail`
class APILoggingMixin(object):
def finalize_response(self, ...):
logger = logging.getLogger(self.__module__)
logger.info('Some message.')