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 django.http import StreamingHttpResponse
19 from catalog.packages.biz.ns_descriptor import create, delete_single, download, query_multiple, query_single, upload
20 from catalog.packages.serializers.create_nsd_info_request import CreateNsdInfoRequestSerializer
21 from catalog.packages.serializers.nsd_info import NsdInfoSerializer
22 from catalog.packages.serializers.nsd_infos import NsdInfosSerializer
23 from catalog.pub.exceptions import CatalogException
24 from drf_yasg.utils import no_body, swagger_auto_schema
25 from rest_framework import status
26 from rest_framework.decorators import api_view
27 from rest_framework.response import Response
29 logger = logging.getLogger(__name__)
34 operation_description="Query a NSD",
37 status.HTTP_200_OK: NsdInfoSerializer(),
38 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
43 operation_description="Delete a NSD",
46 status.HTTP_204_NO_CONTENT: None,
47 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
50 @api_view(http_method_names=['GET', 'DELETE'])
51 def ns_info_rd(request, nsdInfoId): # TODO
52 if request.method == 'GET':
54 data = query_single(nsdInfoId)
55 nsd_info = validate_data(data, NsdInfoSerializer)
56 return Response(data=nsd_info.data, status=status.HTTP_200_OK)
57 except CatalogException as e:
58 logger.error(e.message)
59 error_msg = {'error': 'Query of a NSD failed.'}
60 except Exception as e:
61 logger.error(e.message)
62 logger.error(traceback.format_exc())
63 error_msg = {'error': 'Query of a NSD failed.'}
64 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
66 if request.method == 'DELETE':
68 delete_single(nsdInfoId)
69 return Response(status=status.HTTP_204_NO_CONTENT)
70 except CatalogException as e:
71 logger.error(e.message)
72 error_msg = {'error': 'Deletion of a NSD failed.'}
73 except Exception as e:
74 logger.error(e.message)
75 logger.error(traceback.format_exc())
76 error_msg = {'error': 'Deletion of a NSD failed.'}
77 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
82 operation_description="Create a NSD",
83 request_body=CreateNsdInfoRequestSerializer(),
85 status.HTTP_201_CREATED: NsdInfoSerializer(),
86 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
91 operation_description="Query multiple NSDs",
94 status.HTTP_200_OK: NsdInfosSerializer(),
95 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
98 @api_view(http_method_names=['POST', 'GET'])
99 def ns_descriptors_rc(request, *args, **kwargs):
100 if request.method == 'POST':
102 create_nsd_info_requst = validate_data(request.data, CreateNsdInfoRequestSerializer)
103 data = create(create_nsd_info_requst.data)
104 nsd_info = validate_data(data, NsdInfoSerializer)
105 return Response(data=nsd_info.data, status=status.HTTP_201_CREATED)
106 except CatalogException as e:
107 logger.error(e.message)
108 error_msg = {'error': 'Creating a NSD failed.'}
109 except Exception as e:
110 logger.error(e.message)
111 logger.error(traceback.format_exc())
112 error_msg = {'error': 'Creating a NSD failed.'}
113 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
115 if request.method == 'GET':
117 data = query_multiple()
118 nsd_infos = validate_data(data, NsdInfosSerializer)
119 return Response(data=nsd_infos.data, status=status.HTTP_200_OK)
120 except CatalogException as e:
121 logger.error(e.message)
122 error_msg = {'error': 'Query of multiple NSDs failed.'}
123 except Exception as e:
124 logger.error(e.message)
125 logger.error(traceback.format_exc())
126 error_msg = {'error': 'Query of multiple NSDs failed.'}
127 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
130 @swagger_auto_schema(
132 operation_description="Upload NSD content",
133 request_body=no_body,
135 status.HTTP_204_NO_CONTENT: 'PNFD file',
136 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
139 @swagger_auto_schema(
141 operation_description="Download NSD content",
142 request_body=no_body,
144 status.HTTP_204_NO_CONTENT: None,
145 status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
148 @api_view(http_method_names=['PUT', 'GET'])
149 def nsd_content_ru(request, *args, **kwargs):
150 nsd_info_id = kwargs.get("nsdInfoId")
151 if request.method == 'PUT':
152 files = request.FILES.getlist('file')
154 upload(files[0], nsd_info_id)
155 return Response(data=None, status=status.HTTP_204_NO_CONTENT)
156 except Exception as e:
157 logger.error(e.message)
158 logger.error(traceback.format_exc())
159 error_msg = {'error': 'Uploading NSD content failed.'}
160 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
162 if request.method == 'GET':
164 file_path, file_name, file_size = download(nsd_info_id)
165 start, end = 0, file_size
166 file_range = request.META.get('RANGE')
168 [start, end] = file_range.split('-')
169 start, end = start.strip(), end.strip()
170 start, end = int(start), int(end)
171 response = StreamingHttpResponse(
172 read_partial_file(file_path, start, end),
173 status=status.HTTP_200_OK
175 response['Content-Range'] = '%s-%s' % (start, end)
176 response['Content-Disposition'] = 'attachment; filename=%s' % file_name.encode('utf-8')
177 response['Content-Length'] = end - start
179 except Exception as e:
180 logger.error(e.message)
181 logger.error(traceback.format_exc())
182 error_msg = {'error': 'Downloading NSD content failed.'}
183 return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
186 def read_partial_file(file_path, start, end):
187 fp = open(file_path, 'rb')
190 CHUNK_SIZE = 1024 * 8
191 while pos + CHUNK_SIZE < end:
192 yield fp.read(CHUNK_SIZE)
194 yield fp.read(end - pos)
197 def validate_data(data, serializer):
198 serialized_data = serializer(data=data)
199 if not serialized_data.is_valid():
200 logger.error('Data validation failed.')
201 raise CatalogException(serialized_data.error)
202 return serialized_data