oss_utils.py
3.51 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
# -*- 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 os
import time
import uuid
from datetime import datetime, timedelta, timezone
import oss2
from config import Config
_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}"