-When you create a file upload endpoint using django, the procedure to put the acquired file object into MinIO (https://min.io/) as it is --Memorandum
--Environment - python: v.3.7.7 - django: v.2.0.3 - minio: 5.0.13
Template --Prepare a template for simple upload
{% extends 'base.html' %} //Load the base if necessary
{% block content %}
//Enctype description is required for file upload
<form method="POST" action="{% url 'upload_to_minio' %}" enctype="multipart/form-data">
{% csrf_token %}
//Input for file upload
<p>
<label for="myfile">File:</label>
<input type="file" name="myfile" required id="myfile">
</p>
//Upload button
<button type=“submit”>upload</button>
</form>
{% endblock %}
urs.py --Set the URL for the upload endpoint
urlpatterns = [
path("umc/upload_to_minio/", views.UploadToMinio.as_view(), name="upload_to_minio"
]
views.py --Write the logic to get the uploaded file information and store it in MinIO
class UploadToMinio(generic.View, LoginRequiredMixin):
def post(self, request, *args, **kwargs):
try:
#The uploaded file is a request.Stored in FILES
myfile = self.request.FILES['myfile']
#Read the binary data of the file into memory
#Be careful when handling huge files
file_obj = myfile.read()
#Get file size
file_size = myfile.size
#Bucket name of storage destination
bucket_name = 'hoge'
#Storage destination object name
object_name = 'fuga'
# minio client
minioClient = Minio(
'host:port', #MinIO access destination
access_key='access_key', #Access for each environment_key
secret_key='secret_key', #Secret of each environment_key
secure=True) #True for https communication
#Create bucket if it doesn't exist
if not minioClient.bucket_exists(project_id):
minioClient.make_bucket(bucket_name=bucket_name)
#Creating an object
minioClient.put_object(
bucket_name=project_id,
object_name=uuid,
data=io.BytesIO(file_obj),
length=file_size
)
--data
in put_object
only accepts objects that inherit from ʻio.RawIOBase. Therefore, the object in memory is converted to a binary stream with ʻio.BytesIO ()
.
This should work
Recommended Posts