Django admin实现图片上传到腾讯云

官网参考:https://docs.djangoproject.com/zh-hans/3.2/howto/custom-file-storage/

当前业务需要使用django的admin后台进行数据的管理,需要实现文件的上传云端-腾讯云

 

具体实现:

安装依赖包:
pip install cos-python-sdk-v5==1.9.10

 

自定义一个存储类:

 1)继承Django.core.files.storage.Storage

2)重写save方法

3)添加装饰器,方便进行数据库文件的迁移django.utils.deconstruct.deconstructible

 

demo:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from qcloud_cos import CosConfig, CosS3Client

from .common import generate_img_url


secret_id = settings.OSS_QCLOUD_SECRET_ID
secret_key = settings.OSS_QCLOUD_SECRET_KEY
region = settings.OSS_QCLOUD_REGION
bucket = settings.OSS_QCLOUD_BUCKET
token = settings.OSS_QCLOUD_TOKEN
scheme = settings.OSS_QCLOUD_SCEHME
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
client = CosS3Client(config)
host = settings.OSS_PREFIX

@deconstructible
class CosStorage(Storage):

    def save(self, name, content, max_length=None):
        """
        重写save方法
        """
        # suffix = name.split('.')[-1]
        # key = self.generate_key(suffix)
        key = generate_img_url(name)
        try:
            response = client.put_object(
                Bucket=bucket,
                Body=content.read(),
                Key=key,
                StorageClass='STANDARD',
                EnableMD5=True
            )
        except Exception as e:
            raise
        return host + key

    def url(self, name):
        return name

配置文件中需要添加配置项:

OSS_QCLOUD_SECRET_ID = 'sercret-id'
OSS_QCLOUD_SECRET_KEY = 'secret-key'
OSS_QCLOUD_REGION = '所选区域'
OSS_QCLOUD_BUCKET = '创建的bucket'
OSS_QCLOUD_TOKEN = None
OSS_QCLOUD_SCEHME = 'https'
OSS_NAMESPACE = '可以区分场景'
OSS_PREFIX = 'https://xxx.cos.所选区域.myqcloud.com'

 

公共方法:

# 生成图片路径
def generate_img_url(file_name, scene='default'):
    file_ext = file_name.rsplit('.', 1)[-1]
    new_file_name = scene + '_' + str(datetime.datetime.today()).replace('-', '').replace(' ', '_').replace(':', '') + '.' + file_ext
    namespace = settings.OSS_NAMESPACE
    return f'/{namespace}/' + new_file_name

 

 

最后添加到model中定义的字段中

file = models.FileField(verbose_name='文件', storage=CosStorage())


# 注意:这里使用的FileField   如果是图片的话可以使用ImageField

 

 

参考:https://www.jianshu.com/p/cb7a7f31e962

 

上一篇:CAD如何调整虚线的间距


下一篇:云湖共生-释放企业数据价值