Django 类视图 添加装饰器

今天优化代码的时候想到用装饰器精简函数执行的计时代码,想要把装饰器加到类视图中,在成哥的指导下,完成了

from functools import wraps

def count_time_cost(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = datetime.datetime.now()
        r = func(*args, **kwargs)
        end = datetime.datetime.now()
        LOG.info("Django view function run finished! Task_message : {} Cost_time : {}".format(r.data.get("msg"),
                                                                                              (end - start)))
        return r
    return wrapper
class VolumeQueryNew(APIView):
    @method_decorator(count_time_cost)
    def get(self, request, *args, **kwargs):
        zone_id = request.query_params.get("zoneid")
        volume_uuid = request.query_params.get("volume_uuid") or request.query_params.get("volume_id")
        rc = get_rc_by_udc(request)
        add_mark = "1"
        volume_filtered_info = []
        try:
            msg = 'Get all volume info successfully!'
            LOG.info("volumes info is{}".format(str(volume_filtered_info)))
            pagination_class = APIViewPagePagination
            return common_page_response(volume_filtered_info, request, msg, pagination_class)
        except Exception as e:
            LOG.exception("failed to get volumes!error exception msg{}".format(e))
            return common_error_response("failed to get volumes!error msg",
                                         FAILED_TO_GET_ALL_VOLUMES)

参考:
https://docs.djangoproject.com/en/1.8/topics/class-based-views/intro/#decorating-the-class

http://www.jb51.net/article/61454.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值