Django自定义storage上传文件到Minio
首先新建一个MyStorage.py,自定义Storage类
from io import BytesIO from django.core.files.storage import Storage
from django.conf import settings from utils.minioClient import go_upload_file, go_delete_file, go_upload_file_have_size
from utils.tools import img_bucket class MinioStorage(Storage):
"""
自定义文件存储系统
"""
def __init__(self):
pass def _open(self, name, mode='rb'):
"""
用于打开文件
:param name: 要打开的文件的名字
:param mode: 打开文件方式
:return: None
"""
pass def _save(self, name, content):
"""
用于保存文件
:param name: 要保存的文件名字
:param content: 要保存的文件的内容
:return: None
"""
# print(name)
name = name.replace('\\', '/')
# ret = go_upload_file(BytesIO(content.read()), bucket=img_bucket, path_name=name)
ret = go_upload_file_have_size(BytesIO(content.read()), content.size, bucket=img_bucket, path_name=name)
assert ret == 1, '文件上传失败'
path = '/' + name
return path def delete(self, name):
# im = get_file_path(instance.img)
# print(name)
# name = str(name).split('/')[-1]
ret = go_delete_file(bucket=img_bucket, path_name=str(name))
# print(ret) def url(self, name):
"""
返回name所指文件的绝对URL
:param name: 要读取文件的引用
:return:
"""
host = settings.MINIOHTTP + settings.MINIOWEBHOST + ':' + settings.MINIOWEBPORT
return host + "/" + img_bucket + name def exists(self, name):
"""
检查文件存在
"""
return False
这么实现 def url(self, name)这个函数,需要在Minio后台将 bucket 权限设置为public,就是开放的所有人皆可访问
Minio实现上传文件,新建minioClient.py
import copy
import os from django.conf import settings
from minio import Minio MINIO_CONF = {
'endpoint': settings.MINIOHOST + ':' + settings.MINIOPORT,
'access_key': settings.MINIOUSER,
'secret_key': settings.MINIOPWD,
'secure': False
} client = Minio(**MINIO_CONF) def get_file_size(file):
"""
获取文件大小
file: bytes
return: int
"""
file.seek(0, os.SEEK_END)
return file.tell()
# im = io.BytesIO(file)
# return im.getbuffer().nbytes def go_upload_file(file, bucket='media', path_name=''):
"""
上传文件
"""
try:
# print(path_name)
# print(type(file))
file_len = get_file_size(copy.copy(file))
# print(file_len)
client.put_object(bucket_name=bucket, object_name=path_name, data=file, length=file_len)
return 1
except Exception as e:
print(e)
return 0 def go_upload_file_have_size(file, size, bucket='media', path_name=''):
"""
上传文件,已有文件大小
"""
try:
client.put_object(bucket_name=bucket, object_name=path_name, data=file, length=size)
return 1
except Exception as e:
print(e)
return 0 def go_delete_file(bucket='media', path_name=''):
"""
删除文件
"""
try:
# print(bucket, path_name)
client.remove_object(bucket_name=bucket, object_name=path_name)
return 1
except Exception as e:
print(e)
return 0 def go_delete_file_list(bucket='media', path_name_list=[]):
"""
删除文件列表
未实现,据说需要删除完遍历结果
"""
try:
ret = client.remove_objects(bucket, path_name_list, bypass_governance_mode=False)
print(ret)
return 1
except Exception as e:
print(e)
return 0 def get_file_url(bucket='media', path_name=''):
"""
获取文件url
"""
try:
url = client.presigned_get_object(bucket_name=bucket, object_name=path_name)
return url
except Exception as e:
print(e)
return None def get_file_path(path):
path = path.split('/')[2:]
final_path = '/'.join(path)
return final_path
新建一个tools.py
import datetime
import os
import random
import time img_type_list = ['.jpg', '.png', '.jpeg']
img_bucket = 'media' def get_secret(request):
"""
获取加密的key
"""
return request.META.get('HTTP_AUTHORIZATION') or 'wchime' def get_time_string():
"""
:return: 20220525140635467912
:PS :并发较高时尾部随机数增加
"""
time_string = str(datetime.datetime.fromtimestamp(time.time())).replace("-", "").replace(" ", "").replace(":","").replace(".", "") + str(random.randint(100, 999))
return time_string def split_file_type(file):
"""
对文件名切割,获取名字和类型
"""
file_li = os.path.splitext(file)
return file_li[0], file_li[1] if __name__ == '__main__':
im = 'a.png'
s = split_file_type(im)
print(s)
我的models.py
class TestImg(models.Model):
name = models.CharField(verbose_name="名字", max_length=256)
img = models.ImageField(upload_to='zzz')
新建一个视图文件
from io import BytesIO
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.utils.decorators import method_decorator
from rest_framework import status, serializers
from rest_framework.response import Response
from ani import models
from utils.decorators import request_decrypt
from utils.myView import MyPagination, MyView, MixinGetList, MixinPostCreateModel, MixinPutUpdateModel, \
MixinDeleteDestroyModel
from utils.tools import split_file_type, img_type_list, get_time_string, img_bucket
class TestImgSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestImg
fields = '__all__'
def create(self, validated_data):
res = models.TestImg.objects.create(**validated_data)
return res
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
if validated_data.get('img', False) is not False:
instance.img = validated_data.get('img')
instance.save()
return instance
@method_decorator(request_decrypt, name='get')
class TestImgView(MyView, MixinGetList):
queryset = models.TestImg.objects.all()
serializer_class = TestImgSerializer
all_serializer_class = TestImgSerializer
filter_class = ['name__icontains']
pagination_class = MyPagination
lookup_field = 'id'
ordeing_field = ('-id',)
def post(self, request, *args, **kwargs):
data = request.data
file_content = data.get('file').read()
file_name = get_time_string() + '.png'
# print(file_content)
content_file = ContentFile(file_content, file_name)
# print(content_file)
data['img'] = content_file
serializer_class = TestImgSerializer
serializer = serializer_class(data=data)
# print(serializer.is_valid())
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def put(self, request, *args, **kwargs):
data = request.data
try:
instance = self.queryset.get(id=data.get(self.lookup_field))
except Exception:
return Response({'state': 'fail', 'msg': '未找到该数据'}, status=status.HTTP_400_BAD_REQUEST)
file = data.get('file')
if file:
file_content = file.read()
file_name = get_time_string() + '.png'
# print(file_content)
content_file = ContentFile(file_content, file_name)
# print(content_file)
data['img'] = content_file
if instance.img:
default_storage.delete(instance.img)
serializer_class = TestImgSerializer
serializer = serializer_class(instance=instance, data=data, partial=True)
# print(serializer.is_valid())
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def delete(self, request, *args, **kwargs):
try:
instance = self.queryset.get(id=request.data.get(self.lookup_field))
except Exception:
return Response({'state': 'fail', 'msg': '未找到数据'}, status=status.HTTP_400_BAD_REQUEST)
default_storage.delete(instance.img)
instance.delete()
return Response({'state': 'success', 'msg': '删除成功'}, status=status.HTTP_204_NO_CONTENT)
在settings.py中加上
DEFAULT_FILE_STORAGE = 'utils.MyStorage.MinioStorage'
整个项目文件结构

postman调用的结果

Django自定义storage上传文件到Minio的更多相关文章
- django 自定义存储上传文件的文件名
一.需求: Django实现自定义文件名存储文件 使文件名看起来统一 避免收到中文文件导致传输.存储等问题 相同的文件也需要使用不同的文件名 二.实现思路: 思路: 生成14位随机字母加数字.后10位 ...
- Django和Ueditor自定义存储上传文件的文件名
django台后默认上传文件名 在不使用分布式文件存储系统等第三方文件存储时,django使用默认的后台ImageField和FileField上传文件名默认使用原文件名,当出现同名时会在后面追加下随 ...
- django实现分片上传文件
目标:利用django实现上传文件功能 1,先设置路由系统 urls.py from django.conf.urls import url,include from django.contrib i ...
- Django之用户上传文件的参数配置
Django之用户上传文件的参数配置 models.py文件 class Xxoo(models.Model): title = models.CharField(max_length=128) # ...
- element-ui上传组件,通过自定义请求上传文件
记录使用element-ui上传组件,通过自定义请求上传文件需要注意的地方. <el-upload ref="uploadMutiple" :auto-upload=&quo ...
- django + dropzone.js 上传文件
1.dropzone.js http://www.dropzonejs.com/ dropzone.js是一个可预览\可定制化的文件拖拽上传,实现AJAX异步上传文件的工具 2.dropzone.js ...
- Django session cookie 上传文件、详解
session 在这里先说session 配置URL from django.conf.urls import patterns, include, url from django.contrib i ...
- 基于element ui 实现七牛云自定义key上传文件,并监听更新上传进度
借助上传Upload 上传组件的 http-request 覆盖默认的上传行为,可以自定义上传的实现 <el-upload multiple ref="sliderUpload&quo ...
- Taro 微信小程序 上传文件到minio
小程序前端上传文件不建议直接引用minio的js npm包,一来是这个包本身较大,会影响小程序的体积,二来是ak sk需要放到前端存储,不够安全,因此建议通过请求后端拿到签名数据后上传. 由于小程序的 ...
- 1. Django系列之Django与ajax上传文件
html代码如下: <div class="form-group"> <label for="exampleInputFile">附件上 ...
随机推荐
- Android笔记--添加联系人
添加联系人(将联系人信息添加到手机的通讯录里面) 方式一:使用ContentResolver方法写入对象,每次一个字段 新创建一个需要加入通讯录的对象(我这里写的比较简单,并不是通讯录的标准格式,就是 ...
- Jetson Xavier NX 试玩 (二)
Jetson Xavier NX 试玩 (二) Hello AI World Inference 人工智能推理模型 0 前言 想玩一玩 jetson 的人工智能功能,官方的 instructional ...
- Linux & 标准C语言学习 <DAY14>
一.头文件 头文件可能会被任意源文件包含,意味着头文件中的内容可能会在多个目标文件中存在,要保证合并时不要冲突 重点:头文件只编写声明语句,不能有定义语句 1.头文件应 ...
- 中国科学院2019年大学生数学夏令营考试试题 选做 (Mathematica练习)
目录 试题 1 6 9 solution to (1) solution to (2) 相关读物 试题 选择性地做一些,没有对答案.能机器算的我就不拿纸笔算了,当然实际考试是笔试... 不定期更新 1 ...
- 第一部分:介绍 Spdlog 日志库
什么是 Spdlog 日志库 Spdlog 是一个 C++ 的日志库,它具有高效.易用.跨平台等特点.它可以写入到控制台.文件等输出目标,支持多种日志级别.多线程安全等功能,非常适合在 C++ 项目中 ...
- STM32 HAL库学习 (2) USART实验
使用STM32F407 串口:PA9.PA10(利用CH340G驱动) 一. stm32f4xx_hal_uart.c 函数说明 HAL_UART_Init 函数 要使用一个外设首先要对它进行初始化, ...
- Java:如何在PowerPoint幻灯片中创建散点图
散点图是通过两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式.散点图将序列显示为一组点,值由点在图表中的位置表示,类别由图表中的不同标记表示,通常用于比较 ...
- vue3 封装el-table时,构造$children(类式写法)
由于业务需求(组件封装),需要在获取el-table下面的el-table-column实例 在 vue2.x 当中直接使用this.$children就可以获取到该实例 但是 vue3.x 弃用了$ ...
- python入门教程之二十四Python MySQL - mysql-connector 驱动
MySQL 是最流行的关系型数据库管理系统,如果你不熟悉 MySQL,可以阅读我们的 MySQL 教程. 本章节我们为大家介绍使用 mysql-connector 来连接使用 MySQL, mysql ...
- 五月二十六日jdbc算法以及数据库
1.在PreparedStatement创建SQL对象后,调用preparedStatement()方法时,通过占位符?来按照索引进行SQL语句动态执行通过setString()方法和setInt() ...