Django 類檢視 新增裝飾器
阿新 • • 發佈:2018-12-23
今天優化程式碼的時候想到用裝飾器精簡函式執行的計時程式碼,想要把裝飾器加到類檢視中,在成哥的指導下,完成了
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