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