java中的接口是类吗
297
2022-08-31
Django admin实现图片上传到腾讯云(django vue)
官网参考: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 settingsfrom django.core.files.storage import Storagefrom django.utils.deconstruct import deconstructiblefrom qcloud_cos import CosConfig, CosS3Clientfrom .common import generate_img_urlsecret_id = settings.OSS_QCLOUD_SECRET_IDsecret_key = settings.OSS_QCLOUD_SECRET_KEYregion = settings.OSS_QCLOUD_REGIONbucket = settings.OSS_QCLOUD_BUCKETtoken = settings.OSS_QCLOUD_TOKENscheme = settings.OSS_QCLOUD_SCEHMEconfig = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)host = settings.OSS_PREFIX@deconstructibleclass 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 = NoneOSS_QCLOUD_SCEHME = '= '可以区分场景'OSS_PREFIX = '生成图片路径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://jianshu.com/p/cb7a7f31e962
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~