Created
May 16, 2020 15:24
-
-
Save myers/786ce354094255ce10fac91f7db20ad8 to your computer and use it in GitHub Desktop.
Simple Django 2.2 Middleware that handles file uploads via PUT requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import QueryDict | |
from django.http.multipartparser import MultiValueDict | |
from django.core.files.uploadhandler import ( | |
SkipFile, | |
StopFutureHandlers, | |
StopUpload, | |
) | |
class PutUploadMiddleware(object): | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
method = request.META.get("REQUEST_METHOD", "").upper() | |
if method == "PUT": | |
self.handle_PUT(request) | |
return self.get_response(request) | |
def handle_PUT(self, request): | |
content_type = str(request.META.get("CONTENT_TYPE", "")) | |
content_length = int(request.META.get("CONTENT_LENGTH", 0)) | |
file_name = request.path.split("/")[-1:][0] | |
field_name = file_name | |
content_type_extra = None | |
if content_type == "": | |
return HttpResponse(status=400) | |
if content_length == 0: | |
# both returned 0 | |
return HttpResponse(status=400) | |
content_type = content_type.split(";")[0].strip() | |
try: | |
charset = content_type.split(";")[1].strip() | |
except IndexError: | |
charset = "" | |
upload_handlers = request.upload_handlers | |
for handler in upload_handlers: | |
result = handler.handle_raw_input( | |
request.body, | |
request.META, | |
content_length, | |
boundary=None, | |
encoding=None, | |
) | |
counters = [0] * len(upload_handlers) | |
for handler in upload_handlers: | |
try: | |
handler.new_file( | |
field_name, | |
file_name, | |
content_type, | |
content_length, | |
charset, | |
content_type_extra, | |
) | |
except StopFutureHandlers: | |
break | |
for chunk in request: | |
for i, handler in enumerate(upload_handlers): | |
chunk_length = len(chunk) | |
chunk = handler.receive_data_chunk(chunk, counters[i]) | |
counters[i] += chunk_length | |
if chunk is None: | |
# Don't continue if the chunk received by | |
# the handler is None. | |
break | |
for i, handler in enumerate(upload_handlers): | |
file_obj = handler.file_complete(counters[i]) | |
if file_obj: | |
# If it returns a file object, then set the files dict. | |
request.FILES.appendlist(file_name, file_obj) | |
break | |
any(handler.upload_complete() for handler in upload_handlers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment