Python django.core.files.uploadedfile.UploadedFile() Examples

The following are 25 code examples of django.core.files.uploadedfile.UploadedFile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.files.uploadedfile , or try the search function .
Example #1
Source File: fields.py    From django-private-storage with Apache License 2.0 8 votes vote down vote up
def clean(self, *args, **kwargs):
        data = super(PrivateFileField, self).clean(*args, **kwargs)
        file = data.file
        if isinstance(file, UploadedFile):
            # content_type is only available for uploaded files,
            # and not for files which are already stored in the model.
            content_type = file.content_type

            if self.content_types and content_type not in self.content_types:
                logger.debug('Rejected uploaded file type: %s', content_type)
                raise ValidationError(self.error_messages['invalid_file_type'])

            if self.max_file_size and file.size > self.max_file_size:
                raise ValidationError(self.error_messages['file_too_large'].format(
                    max_size=filesizeformat(self.max_file_size),
                    size=filesizeformat(file.size)
                ))

        return data 
Example #2
Source File: test_briefcase_client.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        TestBase.setUp(self)
        self._publish_transportation_form()
        self._submit_transport_instance_w_attachment()
        src = os.path.join(self.this_directory, "fixtures",
                           "transportation", "screenshot.png")
        uf = UploadedFile(file=open(src), content_type='image/png')
        count = MetaData.objects.count()
        MetaData.media_upload(self.xform, uf)
        self.assertEqual(MetaData.objects.count(), count + 1)
        url = urljoin(
            self.base_url,
            reverse(profile, kwargs={'username': self.user.username})
        )
        self._logout()
        self._create_user_and_login('deno', 'deno')
        self.bc = BriefcaseClient(
            username='bob', password='bob',
            url=url,
            user=self.user
        ) 
Example #3
Source File: configuration.py    From palanaeum with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_config_file(key: str, file: UploadedFile):
    from palanaeum.models import ConfigEntry

    try:
        entry = ConfigEntry.objects.get(key=key)
        if entry.value:
            os.unlink(os.path.join(settings.MEDIA_ROOT, entry.value))
    except ConfigEntry.DoesNotExist:
        entry = ConfigEntry(key=key)
    except FileNotFoundError:
        pass

    file_path = os.path.join(settings.CONFIG_UPLOADS, file.name)
    os.makedirs(settings.CONFIG_UPLOADS, exist_ok=True)
    entry.value = os.path.relpath(file_path, settings.MEDIA_ROOT)

    with open(file_path, mode='wb') as write_file:
        for chunk in file.chunks():
            write_file.write(chunk)

    entry.save()
    cache.set(key, entry.value)
    return 
Example #4
Source File: task_utils.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def normalize(task_id, key, value):
    try:
        json.dumps(value)
        return value
    except TypeError:
        if isinstance(value, models.Model):
            return SimpleObjectSerializer().serialize([value]).pop()
        elif isinstance(value, QuerySet):
            return SimpleObjectSerializer().serialize(value)
        elif isinstance(value, (dict, list, tuple, set)):
            return pre_serialize(task_id, key, value)
        elif isinstance(value, UploadedFile):
            uploaded_file = value  # type: UploadedFile
            cache_key = str(task_id) + '__' + str(key) if key else str(task_id)
            DbCache.put_to_db(cache_key, uploaded_file.read())
            return {
                'file_name': uploaded_file.name,
                'cache_key': cache_key
            }
        return str(value) 
Example #5
Source File: test_edit_user_profile.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def test_upload_avatar_inTemp(self):
        avatar = open(image_path, "rb")
        new_dict = default_dict2.copy()
        new_dict['avatar'] = avatar
        # all images are converted to jpg
        new_file_name = os.path.basename(image_path).partition(".")[0]+".jpg"
        avatar2 = UploadedFile(avatar, name=os.path.basename(image_path), content_type="image/png",
                               size=os.path.getsize(image_path))
        response = self.client.post(reverse('user_profile:edit_profile', kwargs={"username": user_name}),
                                    new_dict, follow=True)
        # NOTE this doesn't verify whether the file has been uploaded successfully
        self.assertContains(response, new_file_name)
        self.delete_image_test()
        avatar.close()

    # helper function 
Example #6
Source File: models_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_resized_images_updated(self):
        """
        thumbnails should be updated if image is already present and updated when update_image=True
        """
        assert self.profile.image
        assert self.profile.image_small
        assert self.profile.image_medium

        # create a dummy image file in memory for upload
        image_file = BytesIO()
        image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
        image.save(image_file, 'png')
        image_file.seek(0)

        self.profile.image = UploadedFile(image_file, "filename.png", "image/png", len(image_file.getvalue()))
        self.profile.save(update_image=True)
        image_file_bytes = image_file.read()
        assert self.profile.image_small.file.read() != image_file_bytes
        assert self.profile.image_medium.file.read() != image_file_bytes 
Example #7
Source File: test_files.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def setUp(self):
        self.files = [open(pwd + "cat1.jpg", "rb"), open(pwd + "cat2.jpg", "rb")]
        self.uploads = [UploadedFile(f, f.name, "image/jpeg", os.path.getsize(f.name)) for f in self.files] 
Example #8
Source File: file.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_jsonable(self, cleaned_data):
        data = {}
        if isinstance(cleaned_data, UploadedFile):
            data['filename'] = cleaned_data.name
            data['size'] = cleaned_data.size
            data['content-type'] = cleaned_data.content_type
            data['charset'] = cleaned_data.charset
            data['secret'] = new_file_secret()
            h = hashlib.sha256()
            for c in cleaned_data.chunks(1000):
                h.update(c)
            data['sha256'] = h.hexdigest()
        return {'data': data, '_file': cleaned_data} 
Example #9
Source File: models.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def pre_save(self, model_instance, add):
        value = super(CloudinaryField, self).pre_save(model_instance, add)
        if isinstance(value, UploadedFile):
            options = {"type": self.type, "resource_type": self.resource_type}
            options.update(self.options)
            instance_value = uploader.upload_resource(value, **options)
            setattr(model_instance, self.attname, instance_value)
            if self.width_field:
                setattr(model_instance, self.width_field, instance_value.metadata.get('width'))
            if self.height_field:
                setattr(model_instance, self.height_field, instance_value.metadata.get('height'))
            return self.get_prep_value(instance_value)
        else:
            return value 
Example #10
Source File: models.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, CloudinaryResource):
            return value
        elif isinstance(value, UploadedFile):
            return value
        elif value is None or value is False:
            return value
        else:
            return self.parse_cloudinary_resource(value) 
Example #11
Source File: admin.py    From dvhb-hybrid with MIT License 5 votes vote down vote up
def clean_picture(self):
        """
        Implements validation of new user picture uploaded
        """

        picture = self.cleaned_data.get('picture')

        # New picture has been uploaded
        if picture and isinstance(picture, UploadedFile):
            # Validate content type
            main, sub = picture.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
                raise forms.ValidationError(
                    _('Please use a JPEG, GIF or PNG image.'))

            w, h = get_image_dimensions(picture)

            # Validate picture dimensions
            max_width = max_height = 1024
            if w > max_width or h > max_height:
                raise forms.ValidationError(_(
                    'Please use an image that is '
                    '%(max_width)sx%(max_height)s pixels or smaller.'
                ) % {'max_width': max_width, 'max_height': max_height})

            # Validate file size
            if len(picture) > (500 * 1024):
                raise forms.ValidationError(
                    _('User picture size may not exceed 500 kB.'))

        return picture 
Example #12
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = hashlib.sha1(value.read()).hexdigest()
        else:
            new_hash = hashlib.sha1(value.encode()).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('') 
Example #13
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def file_upload_view(request):
    """
    A file upload can be updated into the POST dictionary.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)
    if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], str):
        # If a file is posted, the dummy client should only post the file name,
        # not the full path.
        if os.path.dirname(form_data['file_field'].name) != '':
            return HttpResponseServerError()
        return HttpResponse('')
    else:
        return HttpResponseServerError() 
Example #14
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = hashlib.sha1(value.read()).hexdigest()
        else:
            new_hash = hashlib.sha1(value.encode()).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('') 
Example #15
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def file_upload_view(request):
    """
    A file upload can be updated into the POST dictionary.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)
    if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], str):
        # If a file is posted, the dummy client should only post the file name,
        # not the full path.
        if os.path.dirname(form_data['file_field'].name) != '':
            return HttpResponseServerError()
        return HttpResponse('')
    else:
        return HttpResponseServerError() 
Example #16
Source File: models_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super().setUp()

        # create a dummy image file in memory for upload
        image_file = BytesIO()
        image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
        image.save(image_file, 'png')
        image_file.seek(0)

        self.profile.image = UploadedFile(image_file, "filename.png", "image/png", len(image_file.getvalue()))
        self.profile.save(update_image=True) 
Example #17
Source File: storage.py    From django-cloudinary-storage with MIT License 5 votes vote down vote up
def _save(self, name, content):
        name = self._normalise_name(name)
        name = self._prepend_prefix(name)
        content = UploadedFile(content, name)
        response = self._upload(name, content)
        return response['public_id'] 
Example #18
Source File: image_migration.py    From foundation.mozilla.org with Mozilla Public License 2.0 5 votes vote down vote up
def handle(self, *args, **options):

        all_products = Product.objects.all()

        for product in all_products:
            if product.image:
                image = UploadedFile(product.image.file, product.image.file.name)
                product.cloudinary_image = image
                product.save()
                print(f"Product image for {product.name} migrated")
            else:
                print(f"No Product image for {product.name} to migrate") 
Example #19
Source File: djangoforms.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def make_value_from_form(self, value):
    """Convert a form value to a property value.

    This extracts the content from the UploadedFile instance returned
    by the FileField instance.
    """
    if have_uploadedfile and isinstance(value, uploadedfile.UploadedFile):
      if not self.form_value:
        self.form_value = value.read()
      b = db.Blob(self.form_value)
      return b
    return super(BlobProperty, self).make_value_from_form(value) 
Example #20
Source File: test_index.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def zip_file2(self):
        return UploadedFile(open(os.path.join(settings.MEDIA_ROOT, "sample2.zip"), 'r')) 
Example #21
Source File: test_index.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def zip_file1(self):
        return UploadedFile(open(os.path.join(settings.MEDIA_ROOT, "sample.zip"), 'r')) 
Example #22
Source File: models.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_uploaded_file(self, uploaded_file: UploadedFile):
        save_path = pathlib.Path(settings.MEDIA_ROOT, 'sources', str(self.event_id), uploaded_file.name)
        if save_path.exists():
            save_path = save_path.with_name("{}_{}{}".format(save_path.name, time.time(), save_path.suffix))

        save_path.parent.mkdir(parents=True, exist_ok=True, mode=0o775)
        with open(str(save_path), mode='wb') as save_file:
            for chunk in uploaded_file.chunks():
                save_file.write(chunk)

        self.file = str(save_path.relative_to(settings.MEDIA_ROOT))
        return 
Example #23
Source File: views.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _json_write_to_file(parent, field, request, serializer):
    json_serializer = serializer()
    data = json_serializer.validate(request.data)

    # create file object
    with open(json_serializer.filenmame, 'wb+') as f:
        in_memory_file = UploadedFile(
            file=f,
            name=json_serializer.filenmame,
            content_type='application/json',
            size=len(data.encode('utf-8')),
            charset=None
        )

    # wrap and re-open file
    file_obj = QueryDict('', mutable=True)
    file_obj.update({'file': in_memory_file})
    file_obj['file'].open()
    file_obj['file'].seek(0)
    file_obj['file'].write(data.encode('utf-8'))
    serializer = RelatedFileSerializer(
        data=file_obj,
        content_types='application/json',
        context={'request': request}
    )

    serializer.is_valid(raise_exception=True)
    instance = serializer.create(serializer.validated_data)
    setattr(parent, field, instance)
    parent.save(update_fields=[field])

    # Override 'file' return to hide storage details with stored filename
    response = Response(RelatedFileSerializer(instance=instance, content_types='application/json').data)
    response.data['file'] = instance.file.name
    return response 
Example #24
Source File: test_process.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_metadata_file_hash(self):
        self._publish_transportation_form()
        src = os.path.join(self.this_directory, "fixtures",
                           "transportation", "screenshot.png")
        uf = UploadedFile(file=open(src), content_type='image/png')
        count = MetaData.objects.count()
        MetaData.media_upload(self.xform, uf)
        # assert successful insert of new metadata record
        self.assertEqual(MetaData.objects.count(), count + 1)
        md = MetaData.objects.get(xform=self.xform,
                                  data_value='screenshot.png')
        # assert checksum string has been generated, hash length > 1
        self.assertTrue(len(md.hash) > 16) 
Example #25
Source File: uploaders.py    From django-drf-filepond with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def handle_upload(self, request, upload_id, file_id):
        # Since the upload_id and file_id are being provided here as
        # parameters, we check that they are valid. This should be done by
        # the DB and an error would be generated in the tu.save() call below
        # however SQLite doesn't handle field length validation so this won't
        # be picked up when using SQLite.
        if ((not self._file_id_valid(file_id)) or
                (not self._upload_id_valid(upload_id))):
            return Response('Invalid ID for handling upload.',
                            content_type='text/plain',
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        file_obj = self._get_file_obj(request)

        # The type of parsed data should be a descendant of an UploadedFile
        # type.
        if not isinstance(file_obj, UploadedFile):
            raise ParseError('Invalid data type has been parsed.')

        # Save original file name and set name of saved file to the unique ID
        upload_filename = file_obj.name
        file_obj.name = file_id

        # Before we attempt to save the file, make sure that the upload
        # directory we're going to save to exists.
        # *** It's not necessary to explicitly create the directory since
        # *** the FileSystemStorage object creates the directory on save
        # if not os.path.exists(storage.location):
        #    LOG.debug('Filepond app: Creating file upload directory '
        #             '<%s>...' % storage.location)
        #    os.makedirs(storage.location, mode=0o700)

        LOG.debug('About to store uploaded temp file with filename: %s'
                  % (upload_filename))

        # We now need to create the temporary upload object and store the
        # file and metadata.
        tu = TemporaryUpload(upload_id=upload_id, file_id=file_id,
                             file=file_obj, upload_name=upload_filename,
                             upload_type=TemporaryUpload.FILE_DATA,
                             uploaded_by=_get_user(request))
        tu.save()

        response = Response(upload_id, status=status.HTTP_200_OK,
                            content_type='text/plain')

        return response


# Handles chunked file uploads as per the approach described in filepond's
# docs at https://pqina.nl/filepond/docs/patterns/api/server/#process-chunks