@@ -19,13 +19,25 @@ class TosStorage:
|
||||
def __init__(self) -> None:
|
||||
tos = settings.TOS
|
||||
self.bucket = tos["bucket"]
|
||||
config_kwargs = {
|
||||
"signature_version": "s3v4",
|
||||
"s3": {"addressing_style": "virtual"},
|
||||
}
|
||||
try:
|
||||
client_config = Config(
|
||||
**config_kwargs,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
except TypeError:
|
||||
client_config = Config(**config_kwargs)
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=tos["endpoint"],
|
||||
aws_access_key_id=tos["access_key_id"],
|
||||
aws_secret_access_key=tos["secret_access_key"],
|
||||
region_name="cn-shanghai",
|
||||
config=Config(s3={"addressing_style": "virtual"}),
|
||||
region_name=tos.get("region") or "cn-shanghai",
|
||||
config=client_config,
|
||||
)
|
||||
|
||||
def upload_fileobj(self, *, fileobj: BinaryIO, object_key: str, content_type: str) -> StoredObject:
|
||||
@@ -57,6 +69,13 @@ class TosStorage:
|
||||
def public_url(self, *, object_key: str, bucket: str | None = None) -> str:
|
||||
"""桶公读时的虚拟主机式直链:https://{bucket}.{host}/{key}。
|
||||
相比预签名 URL:不签名(省 boto3 客户端/签名开销)、且 URL 稳定可被浏览器/CDN 缓存
|
||||
(签名链每次都变、1h 过期,反而打不到缓存)。仅用于公开可读的预览图。"""
|
||||
host = urlparse(settings.TOS["endpoint"]).netloc
|
||||
return f"https://{bucket or self.bucket}.{host}/{quote(object_key, safe='/')}"
|
||||
(签名链每次都变、1h 过期,反而打不到缓存)。仅用于公开可读的预览图。
|
||||
历史文件的 bucket 仍是火山引擎旧桶,必须用旧域名,不能拼到当前阿里云地址上。"""
|
||||
bucket_name = bucket or self.bucket
|
||||
endpoint = settings.TOS.get("endpoint") or ""
|
||||
legacy_bucket = settings.TOS.get("legacy_bucket") or ""
|
||||
legacy_endpoint = settings.TOS.get("legacy_endpoint") or ""
|
||||
if legacy_bucket and legacy_endpoint and bucket_name == legacy_bucket:
|
||||
endpoint = legacy_endpoint
|
||||
host = urlparse(endpoint).netloc
|
||||
return f"https://{bucket_name}.{host}/{quote(object_key, safe='/')}"
|
||||
|
||||
Reference in New Issue
Block a user