website/www/ccs_upload/views.py
Ben Sturmfels 531a97a3c9
Eliminate "conservancy" and "apps" subdirectories
The directory nesting is unnecessary here and confusing to navigate. I've moved
all apps to the project subdirectory, currently called "www", but soon to be
renamed "conservancy".

I've also moved manage.py to the top-level directory.
2023-10-25 12:36:39 +11:00

38 lines
1.1 KiB
Python

import logging
import os
import random
from django.contrib import messages
from django.shortcuts import redirect, render
from .forms import UploadForm
CCS_UPLOAD_PATH = '/tmp/'
logger = logging.getLogger(__name__)
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
_handle_uploaded_file(file)
messages.add_message(request, messages.INFO, '"{}" was successfully uploaded.'.format(file.name))
return redirect('ccs_upload:form')
else:
form = UploadForm()
return render(request, 'ccs_upload/upload.html', {'form': form})
def _handle_uploaded_file(f):
filename = _hash_prefixed_filename(f.name)
path = os.path.join(CCS_UPLOAD_PATH, filename)
with open(path, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
logger.info('Wrote uploaded file to {}.'.format(path))
def _hash_prefixed_filename(name):
return '{hash:x} {name}'.format(hash=random.getrandbits(32), name=name)