1 # Copyright 2018 ZTE Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from rest_framework import status
19 from rest_framework.response import Response
21 from genericparser.pub.exceptions import GenericparserException
22 from genericparser.pub.exceptions import NsdmBadRequestException
23 from genericparser.pub.exceptions import PackageNotFoundException
24 from genericparser.pub.exceptions import ResourceNotFoundException
25 from genericparser.pub.exceptions import ArtifactNotFoundException
27 logger = logging.getLogger(__name__)
30 def validate_data(data, serializer):
31 serialized_data = serializer(data=data)
32 if not serialized_data.is_valid():
33 logger.error('Data validation failed.')
34 raise GenericparserException(serialized_data.errors)
35 return serialized_data
38 def fmt_error_rsp(error_message, status):
39 return {"errorMessage": error_message, "error": status}
42 def make_error_resp(status, detail):
52 def view_safe_call_with_log(logger):
53 def view_safe_call(func):
54 def wrapper(*args, **kwargs):
56 return func(*args, **kwargs)
57 except PackageNotFoundException as e:
58 logger.error(e.message)
59 return make_error_resp(
61 status=status.HTTP_404_NOT_FOUND
63 except ResourceNotFoundException as e:
64 logger.error(e.message)
65 return make_error_resp(
67 status=status.HTTP_404_NOT_FOUND
69 except ArtifactNotFoundException as e:
70 logger.error(e.message)
71 return make_error_resp(
73 status=status.HTTP_404_NOT_FOUND
75 except NsdmBadRequestException as e:
76 logger.error(e.message)
77 return make_error_resp(
79 status=status.HTTP_400_BAD_REQUEST
81 except GenericparserException as e:
82 logger.error(e.message)
83 return make_error_resp(
85 status=status.HTTP_500_INTERNAL_SERVER_ERROR
87 except Exception as e:
88 logger.error(e.message)
89 logger.error(traceback.format_exc())
90 return make_error_resp(
91 detail='Unexpected exception',
92 status=status.HTTP_500_INTERNAL_SERVER_ERROR