1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import requests
from django.conf import settings
class DownloadFunc(object):
base_path = settings.DOWNLOAD_IMAGE_PATH
@staticmethod
def get_file_base_path(sole_id=None):
dir_path = os.path.join(DownloadFunc.base_path, sole_id)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
return dir_path
@staticmethod
def format_file_abs_path_and_name(dir_path, file_name):
"""
拼接文件绝对地址
:param dir_path: 地址
:param file_name: 文件名
:return:
"""
return os.path.join(dir_path, file_name)
@staticmethod
def get_url_content(url):
"""
:param url:
:return:
"""
content = b''
for _ in range(3):
try:
response = requests.get(url, timeout=10)
return response.content
except:
raise Exception('download failed')
return content
@classmethod
def download_resources(cls, url, sole_id, suffix=""):
"""
下载文件资源
:param url: 下载地址
:param sole_id: 唯一id
:param suffix: 后缀
:return:
"""
_content = cls.get_url_content(url)
if _content:
dir_path = cls.get_file_base_path(sole_id)
name = url.rsplit("/", 1)[-1]
if suffix:
name = "{name}.{suffix}".format(name=name, suffix=suffix)
file_path = cls.format_file_abs_path_and_name(dir_path, name)
# 写入本地
with open(file_path, "wb") as w_:
w_.write(_content)
return file_path
raise Exception("write Failed")
download_img_func = DownloadFunc.download_resources
get_dir_path = DownloadFunc.get_file_base_path