oss_utils.py
7.91 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# -*- coding: utf-8 -*-
"""阿里云 OSS 上传封装:数据库只保存 OSS 链接。
支持两种模式:
1. 前端直传(推荐):后端生成 PostObject 签名(policy+signature),前端直接 POST 到 OSS,
AK/SK 不暴露给前端,数据库只保存 OSS 链接。
2. 本地回退:未配置 OSS(环境变量缺失)时保存到本地 uploads/ 目录,便于本地开发调试。
"""
import base64
import hashlib
import hmac
import json
import logging
import os
import threading
import time
import uuid
from datetime import datetime, timedelta, timezone
import oss2
from config import Config
logger = logging.getLogger('oss_utils')
_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 直传签名有效期(秒)
UPLOAD_TOKEN_EXPIRE = 300
def get_oss_base():
"""OSS 访问基础地址(不含 key)"""
if Config.OSS_PUBLIC_URL:
return Config.OSS_PUBLIC_URL.rstrip('/')
return f"https://{Config.OSS_BUCKET}.{Config.OSS_ENDPOINT}"
def build_object_key(filename):
"""生成 OSS 对象 key:data-process/{日期}/{uuid}.{ext},带日期目录、链接简短"""
ext = os.path.splitext(filename)[1] or ''
date_dir = datetime.now().strftime('%Y%m%d')
return f"data-process/{date_dir}/{uuid.uuid4().hex}{ext}"
def generate_upload_token():
"""生成前端直传 OSS 所需的 PostObject 签名参数(服务端签名直传)。
返回的 policy 限定了:目标 bucket、文件大小上限(100M)、key 前缀(data-process/{日期}/)、有效期。
前端仅需拿这些参数 + 文件本身 POST 到 OSS,无需 AK/SK。
"""
expire = int(time.time()) + UPLOAD_TOKEN_EXPIRE
# policy 的 expiration 需为 UTC 时间字符串
expire_utc = datetime.fromtimestamp(expire, tz=timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.000Z')
dir_prefix = f"data-process/{datetime.now().strftime('%Y%m%d')}/"
policy_dict = {
'expiration': expire_utc,
'conditions': [
{'bucket': Config.OSS_BUCKET},
['content-length-range', 0, Config.MAX_CONTENT_LENGTH],
['starts-with', '$key', dir_prefix],
],
}
policy_b64 = base64.b64encode(json.dumps(policy_dict).encode('utf-8')).decode('utf-8')
signature = base64.b64encode(
hmac.new(Config.OSS_ACCESS_KEY_SECRET.encode('utf-8'),
policy_b64.encode('utf-8'), hashlib.sha1).digest()
).decode('utf-8')
return {
'accessKeyId': Config.OSS_ACCESS_KEY_ID,
'policy': policy_b64,
'signature': signature,
'dir': dir_prefix,
'host': get_oss_base(),
'bucket': Config.OSS_BUCKET,
'expire': expire,
}
def _local_fallback_save(file_storage, filename):
"""OSS 未配置时的本地回退:保存到 uploads/ 目录,返回本地 URL"""
folder = os.path.join(Config.UPLOAD_FOLDER, datetime.now().strftime('%Y%m'))
os.makedirs(folder, exist_ok=True)
key = f"{uuid.uuid4().hex}_{filename}"
path = os.path.join(folder, key)
file_storage.save(path)
return f"/uploads/{datetime.now().strftime('%Y%m')}/{key}"
def save_file(file_storage, filename):
"""(后端中转模式)上传文件到 OSS,返回可访问的 URL。
数据库只保存这里返回的 URL。
"""
if not Config.OSS_ENABLED:
return _local_fallback_save(file_storage, filename)
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
key = build_object_key(filename)
bucket.put_object(key, file_storage.stream)
return f"{get_oss_base()}/{key}"
def get_object_key_from_url(file_url):
"""从完整 URL 中提取 OSS object key(去掉域名前缀,返回相对路径)"""
# 如果是本地回退路径(/uploads/...),直接返回该路径作为 key
if file_url.startswith('/uploads/'):
return file_url
oss_base = get_oss_base()
if file_url.startswith(oss_base + '/'):
return file_url[len(oss_base) + 1:]
return file_url
def download_file(file_url, local_path, timeout_seconds=60):
"""从 OSS 下载文件到本地路径,带超时保护。
- 解析 file_url 获取 OSS object key
- 使用 oss2.Bucket.get_object_to_file() 下载
- 本地回退模式:如果 file_url 以 /uploads/ 开头,直接从本地 uploads 目录复制
- 目录不存在时自动创建
- 下载失败时抛出 Exception
- 超时后抛出 TimeoutError
"""
import threading
import time as time_module
download_start = time_module.time()
# 本地回退模式:从本地 uploads 目录复制
if file_url.startswith('/uploads/'):
source_path = os.path.join(Config.UPLOAD_FOLDER, file_url[len('/uploads/'):])
os.makedirs(os.path.dirname(local_path), exist_ok=True)
if not os.path.exists(source_path):
raise Exception(f"本地文件不存在: {source_path}")
import shutil
shutil.copy2(source_path, local_path)
elapsed = time_module.time() - download_start
logger.info(f"[OSS下载] 本地复制完成: {file_url}, 耗时: {elapsed:.2f}s")
return
if not Config.OSS_ENABLED:
raise Exception("OSS 未启用,无法下载远程文件")
# 从 URL 中解析 object key
object_key = get_object_key_from_url(file_url)
# 确保本地目录存在
os.makedirs(os.path.dirname(local_path), exist_ok=True)
logger.info(f"[OSS下载] 开始下载: url={file_url[:80]}..., timeout={timeout_seconds}s")
# 使用线程实现超时控制
result = {'error': None}
def _do_download():
try:
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
bucket.get_object_to_file(object_key, local_path)
except Exception as e:
result['error'] = str(e)
download_thread = threading.Thread(target=_do_download, daemon=True)
download_thread.start()
download_thread.join(timeout=timeout_seconds)
if download_thread.is_alive():
elapsed = time_module.time() - download_start
raise TimeoutError(f"下载超时: {file_url[:80]}, 超过 {timeout_seconds}s (实际耗时 {elapsed:.2f}s)")
if result['error']:
raise Exception(f"OSS 下载失败: {result['error']}")
elapsed = time_module.time() - download_start
logger.info(f"[OSS下载] 下载完成: url={file_url[:80]}..., 耗时: {elapsed:.2f}s")
def upload_file(local_path, object_key=None):
"""上传本地文件到 OSS,返回可访问的 URL。
- 如果未配置 OSS,走本地回退模式(复制到 uploads 目录)
- 配置 OSS 时,使用 oss2.Bucket.put_object() 上传
- 返回可访问的 URL(完整路径)
"""
filename = os.path.basename(local_path)
if not Config.OSS_ENABLED:
# 本地回退:复制到 uploads 目录
folder = os.path.join(Config.UPLOAD_FOLDER, datetime.now().strftime('%Y%m'))
os.makedirs(folder, exist_ok=True)
key = object_key or f"{uuid.uuid4().hex}_{filename}"
dest_path = os.path.join(folder, key)
import shutil
shutil.copy2(local_path, dest_path)
return f"/uploads/{datetime.now().strftime('%Y%m')}/{key}"
# 使用 OSS 上传
if object_key is None:
object_key = build_object_key(filename)
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
# 注意:put_object(key, data) 的 data 为 str 时会把字符串本身当内容上传。
# 这里 local_path 是本地文件路径,必须用 put_object_from_file 按字节读取上传,
# 否则 OSS 上存的是路径文本而非真实文件(导出文件会变成一串本地路径字符串)。
bucket.put_object_from_file(object_key, local_path)
return f"{get_oss_base()}/{object_key}"