def mkdir(path):
path = path.strip()
path = path.rstrip("\")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
return True
else:
return False
def down_load_img(imgUrl, imgName=''):
if not imgName:
imgName = int(time.time()) + random.randint(0, 999999)
file_suffix = os.path.splitext(imgUrl)[1]
file_suffix = file_suffix if file_suffix else '.jpg'
save_folder = time.strftime(r"%Y%m%d", time.localtime(int(time.time())))
SAVE_ROOT_PATH = '/expressell/public/uploads/products/' + save_folder
mkdir(SAVE_ROOT_PATH)
save_img_path = SAVE_ROOT_PATH + '/' + str(imgName) + str(file_suffix)
try:
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
img = requests.get(imgUrl, headers=header, timeout=timeout)
if img.status_code == 200:
with open(save_img_path, 'wb') as f:
f.write(img.content)
print(imgUrl, '下载成功')
return save_img_path
else:
print(imgUrl, '下载失败,', img.status_code)
except Exception as e:
print(imgUrl, "下载图片错误XXXX", e)
try:
os.remove(save_img_path)
except Exception as e:
pass
return False