You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django CloudinaryField:设置默认上传隐私与生成带过期的预签名URL

解决方案

1. 设置默认上传隐私为私有

有两种实现方式,可根据需求选择:

方式一:全局配置(所有CloudinaryField生效)

在项目的settings.py中修改Cloudinary配置,添加上传默认选项:

CLOUDINARY = {
    'cloud_name': '你的云名称',
    'api_key': '你的API密钥',
    'api_secret': '你的API密钥',
    'upload_options': {
        'type': 'private',  # 全局默认上传为私有资源
    }
}

方式二:字段级配置(仅当前Media模型生效)

直接在CloudinaryField中通过options参数指定私有类型:

from django.db import models
from cloudinary.models import CloudinaryField

class Media(models.Model):
    # 其他字段...
    image = CloudinaryField(
        'document', 
        null=True, 
        blank=True, 
        options={'type': 'private'}  # 该字段上传的资源默认私有
    )

设置完成后,新上传的图片会被标记为私有资源,无法通过普通公共URL直接访问,必须使用预签名URL。

2. 生成5分钟过期的预签名URL

在Media模型中添加自定义方法,用于生成带过期时间的预签名URL:

from django.db import models
from django.utils import timezone
from cloudinary.models import CloudinaryField
import cloudinary

class Media(models.Model):
    # 其他字段...
    image = CloudinaryField(
        'document', 
        null=True, 
        blank=True, 
        options={'type': 'private'}
    )

    def get_expiring_presigned_url(self):
        """生成5分钟后过期的预签名访问URL"""
        if not self.image:
            return None
        
        # 计算5分钟后的过期时间点
        expiration_time = timezone.now() + timezone.timedelta(minutes=5)
        
        # 调用Cloudinary工具函数生成预签名URL
        return cloudinary.utils.generate_download_url(
            public_id=self.image.public_id,
            resource_type='image',
            type='private',
            expires_at=expiration_time
        )

使用时直接调用实例方法即可:

media_obj = Media.objects.get(id=1)
valid_presigned_url = media_obj.get_expiring_presigned_url()

注意事项

  • 确保Cloudinary配置中已正确设置api_secret,生成预签名URL必须依赖密钥。
  • 预签名URL仅在指定的过期时间内有效,过期后需重新生成。

内容的提问来源于stack exchange,提问作者Chau Loi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:57:36