Update python2 to python3
[vfc/nfvo/lcm.git] / lcm / ns / views / sol / 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 from lcm.pub.exceptions import SeeOtherException
24
25 logger = logging.getLogger(__name__)
26
27
28 def make_error_resp(status, detail):
29     return Response(
30         data={
31             'status': status,
32             'detail': detail
33         },
34         status=status
35     )
36
37
38 def view_safe_call_with_log(logger):
39     def view_safe_call(func):
40         def wrapper(*args, **kwargs):
41             try:
42                 return func(*args, **kwargs)
43             except SeeOtherException as e:
44                 logger.error(e.args[0])
45                 return make_error_resp(
46                     detail=e.args[0],
47                     status=status.HTTP_303_SEE_OTHER
48                 )
49             except BadRequestException as e:
50                 logger.error(e.args[0])
51                 return make_error_resp(
52                     detail=e.args[0],
53                     status=status.HTTP_400_BAD_REQUEST
54                 )
55             except NSLCMException as e:
56                 logger.error(e.args[0])
57                 return make_error_resp(
58                     detail=e.args[0],
59                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
60                 )
61             except Exception as e:
62                 logger.error(e.args[0])
63                 logger.error(traceback.format_exc())
64                 return make_error_resp(
65                     detail='Unexpected exception',
66                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
67                 )
68         return wrapper
69     return view_safe_call