87cdfd9bde920144273da81e8799cceb6174eda0
[vfc/nfvo/lcm.git] / lcm / pub / utils / fileutil.py
1 # Copyright 2016 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 import os
15 import shutil
16 import logging
17 import traceback
18 import urllib2
19
20 logger = logging.getLogger(__name__)
21
22
23 def make_dirs(path):
24     if not os.path.exists(path):
25         os.makedirs(path, 0o777)
26
27
28 def delete_dirs(path):
29     try:
30         if os.path.exists(path):
31             shutil.rmtree(path)
32     except Exception as e:
33         logger.error(traceback.format_exc())
34         logger.error("Failed to delete %s:%s", path, e.message)
35
36
37 def download_file_from_http(url, local_dir, file_name):
38     local_file_name = os.path.join(local_dir, file_name)
39     is_download_ok = False
40     try:
41         make_dirs(local_dir)
42         r = urllib2.Request(url)
43         req = urllib2.urlopen(r)
44         save_file = open(local_file_name, 'wb')
45         save_file.write(req.read())
46         save_file.close()
47         req.close()
48         is_download_ok = True
49     except:
50         logger.error(traceback.format_exc())
51         logger.error("Failed to download %s to %s.", url, local_file_name)
52     return is_download_ok, local_file_name