code refactor for genericparser
[modeling/etsicatalog.git] / genericparser / packages / biz / common.py
1 # Copyright 2018 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 os
16
17 from genericparser.pub.config.config import GENERICPARSER_ROOT_PATH
18 from genericparser.pub.utils import fileutil
19
20 CHUNK_SIZE = 1024 * 8
21
22
23 def save(remote_file, vnf_pkg_id):
24     local_file_name = remote_file.name
25     local_file_dir = os.path.join(GENERICPARSER_ROOT_PATH, vnf_pkg_id)
26     local_file_name = os.path.join(local_file_dir, local_file_name)
27     if not os.path.exists(local_file_dir):
28         fileutil.make_dirs(local_file_dir)
29     with open(local_file_name, 'wb') as local_file:
30         for chunk in remote_file.chunks(chunk_size=CHUNK_SIZE):
31             local_file.write(chunk)
32     return local_file_name
33
34
35 def read(file_path, start, end):
36     fp = open(file_path, 'rb')
37     fp.seek(start)
38     pos = start
39     while pos + CHUNK_SIZE < end:
40         yield fp.read(CHUNK_SIZE)
41         pos = fp.tell()
42     yield fp.read(end - pos)
43
44
45 def parse_file_range(file_path, file_range):
46     start, end = 0, os.path.getsize(file_path)
47     if file_range:
48         [start, range_end] = file_range.split('-')
49         range_end = range_end.strip() if range_end.strip() else end
50         start, end = int(start.strip()), int(range_end)
51     return start, end