Python mixin可以访问全局变量吗?

时间:2013-05-30 02:05:21

标签: python django mixins

我有一个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变量?

1 个答案:

答案 0 :(得分:2)

意识到APILoggingMixin.finalize_response需要self CategoryDetail实例,我们可以将记录器附加到CategoryDe​​tail

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.')