Refactor codes for manual scale ns
[vfc/nfvo/lcm.git] / lcm / ns / views / deprecated / common.py
1 # Copyright 2019 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import traceback
16 import logging
17
18 from rest_framework import status
19 from rest_framework.response import Response
20
21 from lcm.pub.exceptions import BadRequestException
22 from lcm.pub.exceptions import NSLCMException
23
24 logger = logging.getLogger(__name__)
25
26
27 def make_error_resp(status, detail):
28     return Response(
29         data={
30             'error': detail
31         },
32         status=status
33     )
34
35
36 def view_safe_call_with_log(logger):
37     def view_safe_call(func):
38         def wrapper(*args, **kwargs):
39             try:
40                 return func(*args, **kwargs)
41             except BadRequestException as e:
42                 logger.error(e.args[0])
43                 return make_error_resp(
44                     detail=e.args[0],
45                     status=status.HTTP_400_BAD_REQUEST
46                 )
47             except NSLCMException as e:
48                 logger.error(e.args[0])
49                 return make_error_resp(
50                     detail=e.args[0],
51                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
52                 )
53             except Exception as e:
54                 logger.error(e.args[0])
55                 logger.error(traceback.format_exc())
56                 return make_error_resp(
57                     detail='Unexpected exception',
58                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
59                 )
60         return wrapper
61     return view_safe_call