Django: Загрузка файлов в контейнер хранилища Azure Blob Storage

Я хочу иметь приложение, которое загружает файлы в контейнер Azure Blob Storage. Я начал с приложения, которое загружало файлы в статическую папку media. Теперь я хочу изменить его так, чтобы файлы отправлялись в контейнер. Мне нужно решить три проблемы :

  1. The models.py, where I do not know how I should modify it. What do I do with the moldels.Filefield. I used it to define the folder to upload the file but right now I should not need it, should I ? If I am not wrong, I need it because of my form.

  2. This is my view upload. The view works but I am not sure that I did it the best way to upload to the container. Is it possible to do it in a different more efficient or nicer ?

  3. Should I add something in my settings.py file ?

models.py

class UploadFiles(models.Model):
    
    User = models.CharField(max_length=200) 
    Documents = models.FileField() 
    PreviousFilename = models.CharField(max_length=200) 
    NewFilename = models.CharField(max_length=200) 
    SizeFile = models.IntegerField() 
    Uploaded_at = models.DateTimeField(auto_now_add=True) 

views.py

from io import BytesIO
import os
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from datetime import datetime, timedelta
from dateutil import tz, parser
from base.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token
from base.login_helper import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.conf import settings
from base.forms import FilesForm
from base.models import UploadFiles
from datetime import datetime

from azure.storage.blob import BlobServiceClient


def upload(request):
    
    # INITIALIZE THE CONTEXT TO FIX THE AUTHENTICATION
    context = initialize_context(request)
    username = request.session.get('user').get('name')

    # WE SET THE BLOB STORAGE  PARAMETER
    credential = ""
    account_url = ""
    container = ""

    blob_service_client = BlobServiceClient(account_url= account_url, credential= credential)

    if request.method == 'POST':
        form = FilesForm(request.POST, request.FILES)
        files = request.FILES.getlist('Documents')

        if form.is_valid():
            
            for f in files :
                
                #  THE PREVOUS FILENAME IS STORED
                previous_name = f.name
                content = f.read()
                
                # WE RENAME THE FILE
                ext = f.name.split('.')[-1]
                name = f.name.split('.')[0]
                f.name = "%s_%s.%s" % (name, datetime.now().strftime("%Y%m%d_%H%M%S"),ext)
                file_io =  BytesIO(content)


                blob_client = blob_service_client.get_blob_client(container=container, blob=f.name)
                blob_client.upload_blob(data=file_io)

                newfile = UploadFiles(User=username, Documents=f, PreviousFilename=previous_name, NewFilename=f.name, SizeFile=f.size)
                newfile.save()
    else:
        form = FilesForm()

    # Load files for the list page
    files_list = UploadFiles.objects.all().filter(User=username).order_by('-Uploaded_at')

    # Page
    page = request.GET.get('page', 1)
    paginator = Paginator(files_list, 10)

    try:
        files = paginator.page(page)
    except PageNotAnInteger:
        files = paginator.page(1)
    except EmptyPage:
        files = paginator.page(paginator.num_pages)


    # Load the context
    context['files'] = files
    context['form'] = form
    context['page'] = page

    return render(request, 'base/upload.html', context)

forms.py

from django import forms
from django.forms import ClearableFileInput
from .models import UploadFiles


class FilesForm(forms.ModelForm):
    class Meta:
        model = UploadFiles
        fields = ['Documents']
        widgets = {'Documents': ClearableFileInput(attrs={'multiple': True}),}

Спасибо за ответы

Вернуться на верх