Add: basic upload & serve submission files url endpoint views

This commit is contained in:
Aroy-Art 2023-12-28 19:17:42 +01:00
parent decd00bb6e
commit 43b7030d33
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -0,0 +1,83 @@
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.http import FileResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
import os
import blake3
from .forms import UploadFileForm
from .models import Submission_File
def compute_file_hash(file):
'''
Compute BLAKE3 hash of the file
'''
try:
hasher = blake3.blake3()
for chunk in file.chunks(chunk_size=65536):
hasher.update(chunk)
return hasher.hexdigest()
except Exception as e:
print(f"Error computing file hash: {e}")
return None
@login_required(login_url="/login/")
def serve_submission_file(request, file_hash):
'''
View function to serve submission files for download or inline viewing
'''
download = request.GET.get('d')
try:
submission_file = get_object_or_404(Submission_File, file_hash=file_hash)
file = submission_file.file.file
file_name = submission_file.file_name
response = FileResponse(file)
if download == "1":
response['Content-Disposition'] = f'attachment; filename="{file_name}"'
else:
response['Content-Disposition'] = f'inline; filename="{file_name}"'
return response
except:
return HttpResponse("File not found", status=404)
@login_required(login_url="/login/")
def fileUpload(request):
'''
View function for handling file uploads
'''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = form.cleaned_data['file']
file_name = file.name
file_hash = compute_file_hash(file)
Null, file_ext = os.path.splitext(file_name)
hash_file_name = file_hash + file_ext
new_submission_file, created = Submission_File.objects.get_or_create(file_hash=file_hash)
new_submission_file.file_hash = file_hash
new_submission_file.file_name = file_name
new_submission_file.file.save(hash_file_name, file)
new_submission_file.save
return HttpResponseRedirect("/")
else:
form = UploadFileForm()
return render(request, 'files/upload.html', {'form': form})