Пример #1
0
class WizardExampleview(SessionWizardView):
    form_list = [forms.MultipleFileExampleForm, forms.WizardStepForm]
    file_storage = FileSystemStorage(location=get_upload_path())
    template_name = 'wizard.html'

    def done(self, form_list, **kwargs):
        return HttpResponseRedirect('/wizard')
Пример #2
0
    def patch(self, request, *args, **kwargs):
        response = self.get_tus_response()

        resource_id = kwargs.get('resource_id', None)

        filename = cache.get("tus-uploads/{}/filename".format(resource_id))
        file_size = int(
            cache.get("tus-uploads/{}/file_size".format(resource_id)))
        metadata = cache.get("tus-uploads/{}/metadata".format(resource_id))
        offset = cache.get("tus-uploads/{}/offset".format(resource_id))

        file_offset = int(request.META.get("HTTP_UPLOAD_OFFSET", 0))
        chunk_size = int(request.META.get("CONTENT_LENGTH", 102400))

        upload_file_path = get_upload_path().joinpath(resource_id)
        if filename is None or not upload_file_path.exists():
            response.status_code = 410
            return response

        if file_offset != offset:  # check to make sure we're in sync
            response.status_code = 409  # HTTP 409 Conflict
            return response

        logger.info(
            f"TUS patch resource_id={resource_id} filename={filename} file_size={file_size} metadata={metadata} offset={offset} upload_file_path={upload_file_path}"
        )

        file = None
        try:
            file = upload_file_path.open("r+b")
        except IOError:
            file = upload_file_path.open("wb")
        finally:
            if file:
                file.seek(file_offset)
                file.write(request.body)
                file.close()

        try:
            new_offset = cache.incr(
                "tus-uploads/{}/offset".format(resource_id), chunk_size)
        except ValueError:
            response.status_code = 404
            return response

        response['Upload-Offset'] = new_offset

        response.status_code = 204

        if file_size == new_offset:
            remove_resource_from_cache(resource_id)

            create_uploaded_file_in_db(
                field_name=metadata.get('fieldName'),
                file_id=resource_id,
                form_id=metadata.get('formId'),
                original_filename=metadata.get('filename'),
                uploaded_file=upload_file_path)

        return response
Пример #3
0
def start_upload(request):
    check_permission(request)

    response = get_tus_response()

    if request.META.get("HTTP_TUS_RESUMABLE", None) is None:
        logger.warning(
            "Received File upload for unsupported file transfer protocol")
        response.status_code = 500
        response.reason_phrase = (
            "Received File upload for unsupported file transfer protocol")
        return response

    metadata = {}
    upload_metadata = request.META.get("HTTP_UPLOAD_METADATA", None)

    if upload_metadata:
        for kv in upload_metadata.split(","):
            (key, value) = kv.split(" ")
            metadata[key] = base64.b64decode(value).decode("utf-8")

    logger.info(f"TUS post metadata={metadata}")

    file_size = int(request.META.get("HTTP_UPLOAD_LENGTH", "0"))
    resource_id = str(uuid.uuid4())

    cache.add(
        "tus-uploads/{}/filename".format(resource_id),
        metadata.get("filename"),
        conf.TIMEOUT,
    )
    cache.add("tus-uploads/{}/file_size".format(resource_id), file_size,
              conf.TIMEOUT)
    cache.add("tus-uploads/{}/offset".format(resource_id), 0, conf.TIMEOUT)
    cache.add("tus-uploads/{}/metadata".format(resource_id), metadata,
              conf.TIMEOUT)

    try:
        with Path(get_upload_path()).joinpath(resource_id).open("wb") as f:
            pass
    except IOError as e:
        logger.error(
            "Unable to create file: {}".format(e),
            exc_info=True,
            extra={
                "request": request,
            },
        )
        response.status_code = 500
        return response

    response.status_code = 201
    response["Location"] = "{}{}".format(request.build_absolute_uri(),
                                         resource_id)
    return response
Пример #4
0
class WizardExampleview(SessionWizardView):
    form_list = [forms.MultipleFileExampleForm, forms.WizardStepForm]
    file_storage = FileSystemStorage(location=get_upload_path())
    template_name = "wizard.html"

    def done(self, form_list, **kwargs):
        return HttpResponseRedirect("/wizard")

    def get_context_data(self, **kwargs):
        kwargs["file_form_js"] = file_form_js()
        return super().get_context_data(**kwargs)
Пример #5
0
def cancel_upload(resource_id):
    logger.info(f"TUS delete resource_id={resource_id}")

    remove_resource_from_cache(resource_id)

    upload_file_path = get_upload_path().joinpath(resource_id)

    if upload_file_path.exists():
        upload_file_path.unlink()

    uploaded_file = TemporaryUploadedFile.objects.try_get(file_id=resource_id)

    if uploaded_file:
        uploaded_file.delete()

    response = get_tus_response()
    response.status_code = 204
    return response
Пример #6
0
    def delete(self, request, *args, **kwargs):
        response = self.get_tus_response()
        resource_id = kwargs.get('resource_id', None)

        logger.info(f"TUS delete resource_id={resource_id}")

        upload_file_path = get_upload_path().joinpath(resource_id)

        if upload_file_path.exists():
            upload_file_path.unlink()

        uploaded_file = UploadedFile.objects.try_get(file_id=resource_id)

        if uploaded_file:
            uploaded_file.delete()

        remove_resource_from_cache(resource_id)

        response.status_code = 204 if uploaded_file else 404
        return response
Пример #7
0
 def test_get_upload_path_relative(self):
     self.assertEqual(
         str(get_upload_path()),
         str(Path(settings.MEDIA_ROOT).joinpath("relative/path")),
     )
Пример #8
0
 def test_get_upload_path_absolute(self):
     self.assertEqual(str(get_upload_path()), "/absolute/path")