def test_get_prep_value(self):
     res = CloudinaryResource(metadata=self.uploaded)
     value = "image/upload/v{version}/{id}.{format}".format(
         version=self.uploaded["version"],
         id=self.uploaded["public_id"],
         format=self.uploaded["format"])
     self.assertEqual(value, res.get_prep_value())
 def test_get_presigned(self):
     res = CloudinaryResource(metadata=self.uploaded)
     value = "image/upload/v{version}/{id}.{format}#{signature}".format(version=self.uploaded["version"],
                                                                        id=self.uploaded["public_id"],
                                                                        format=self.uploaded["format"],
                                                                        signature=self.uploaded["signature"])
     self.assertEqual(value, res.get_presigned())
示例#3
0
 def test_to_python(self):
     c = CloudinaryField('image')
     res = CloudinaryResource(public_id=API_TEST_ID, format='jpg')
     # Can't compare the objects, so compare url instead
     self.assertEqual(
         c.to_python('{}.jpg'.format(API_TEST_ID)).build_url(),
         res.build_url())
 def test_image(self):
     res = CloudinaryResource(metadata=self.uploaded)
     image = res.image()
     self.assertRegexpMatches(image, '[^-]src="{url}'.format(url=res.url))
     self.assertNotRegexpMatches(image, 'data-src="{url}'.format(url=res.url))
     image = res.image(responsive=True, width="auto", crop="scale")
     self.assertNotRegexpMatches(image, '[^-]src="{url}'.format(url=res.build_url(width="auto", crop="scale")))
     self.assertRegexpMatches(image, 'data-src="{url}'.format(url=res.build_url(width="auto", crop="scale")))
示例#5
0
def cloudinary_tag(context, image, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(image, CloudinaryResource):
        image = CloudinaryResource(image)
    return image.image(**options)
示例#6
0
def cloudinary_url(context, source, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(source, CloudinaryResource):
        source = CloudinaryResource(source)
    return source.build_url(**options)
示例#7
0
def cloudinary_tag(context, image, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(image, CloudinaryResource):
        image = CloudinaryResource(image)
    return image.image(**options)
示例#8
0
def cloudinary_url(context, source, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(source, CloudinaryResource):
        source = CloudinaryResource(source)
    return source.build_url(**options)
def cloudinary_static(context, image, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(image, CloudinaryResource):
        image = staticfiles_storage.stored_name(image)
        image = CloudinaryResource(image)
    return mark_safe(image.image(**options))
def cloudinary_static(context, image, options_dict={}, **options):
    options = dict(options_dict, **options)
    try:
        if context['request'].is_secure() and 'secure' not in options:
            options['secure'] = True
    except KeyError:
        pass
    if not isinstance(image, CloudinaryResource):
        image = staticfiles_storage.stored_name(image)
        image = CloudinaryResource(image)
    return mark_safe(image.image(**options))
示例#11
0
 def to_python(self, value):
     """Convert to CloudinaryResource"""
     if not value:
         return None
     if value.split("/")[0] != "image":
         return None
     m = re.search(r'^([^/]+)/([^/]+)/v(\d+)/([^#]+)#([^/]+)$', value)
     if not m:
         raise forms.ValidationError("Invalid format")
     resource_type = m.group(1)
     upload_type = m.group(2)
     version = m.group(3)
     filename = m.group(4)
     signature = m.group(5)
     m = re.search(r'(.*)\.(.*)', filename)
     if not m:
         raise forms.ValidationError("Invalid file name")
     public_id = m.group(1)
     image_format = m.group(2)
     return CloudinaryResource(public_id,
                               format=image_format,
                               version=version,
                               signature=signature,
                               type=upload_type,
                               resource_type=resource_type)
    def test_empty_class(self):
        """An empty CloudinaryResource"""

        self.shortDescription()
        res = CloudinaryResource()
        self.assertFalse(res, "should be 'False'")
        self.assertEqual(len(res), 0, "should have zero len()")
        self.assertIsNone(res.url, "should have None url")
示例#13
0
 def parse_cloudinary_resource(self, value):
     m = re.match(CLOUDINARY_FIELD_DB_RE, value)
     resource_type = m.group('resource_type') or self.resource_type
     upload_type = m.group('type') or self.type
     return CloudinaryResource(type=upload_type,
                               resource_type=resource_type,
                               version=m.group('version'),
                               public_id=m.group('public_id'),
                               format=m.group('format'))
示例#14
0
 def to_python(self, value):
     if isinstance(value, CloudinaryResource):
         return value
     elif isinstance(value, UploadedFile):
         return value
     elif not value:
         return value
     else:
         m = re.match(CLOUDINARY_FIELD_DB_RE, value)
         resource_type = m.group('resource_type') or self.resource_type
         type = m.group('type') or self.type
         return CloudinaryResource(type=type,resource_type=resource_type,version=m.group('version'),public_id=m.group('public_id'),format=m.group('format'))
 def test_image(self):
     res = CloudinaryResource(metadata=self.uploaded)
     image = res.image()
     self.assertRegexpMatches(image, '[^-]src="{url}'.format(url=res.url))
     self.assertNotRegexpMatches(image, 'data-src="{url}'.format(url=res.url))
     image = res.image(responsive=True, width="auto", crop="scale")
     self.assertNotRegexpMatches(image, '[^-]src="{url}'.format(url=res.build_url(width="auto", crop="scale")))
     self.assertRegexpMatches(image, 'data-src="{url}'.format(url=res.build_url(width="auto", crop="scale")))
示例#16
0
    def _attach_file(self, file: File, **options):
        cloudinary_options = self.get_cloudinary_options()
        cloudinary_options.update(options.get('cloudinary', {}))

        if file.size >= 100 * 1024 * 1024:
            upload = uploader.upload_large
        else:
            upload = uploader.upload

        file_field = self.get_file_field()

        try:
            result = upload(
                file,
                type=file_field.type,
                resource_type=file_field.resource_type,
                **cloudinary_options,
            )
        except cloudinary.exceptions.Error as e:
            if e.args and 'Unsupported file type' in e.args[0]:
                raise exceptions.UnsupportedFileError(
                    _('File `%s` is not an image') % file.name)
            else:
                raise ValidationError(*e.args)

        # fix difference between `public_id` in response
        # and `public_id` in CloudinaryField
        file_format = result.get("format")
        if file_format:
            public_id = result["public_id"]
        else:
            public_id, file_format = posixpath.splitext(result["public_id"])
            file_format = file_format.lstrip('.')

        resource = CloudinaryResource(
            public_id,
            version=str(result["version"]),
            format=file_format,
            type=result["type"],
            resource_type=result["resource_type"],
            metadata=result,
        )

        self.set_file(resource)

        self.basename = helpers.get_filename(file.name)
        self.extension = file_format or ''
        return result
示例#17
0
    def photo(self, request, pk=None):
        file = request.data.get('image')

        u = cloudinary_uploader.upload(file)

        instance = self.get_object()
        instance.avatar = CloudinaryResource(u['public_id'],
                                             u['format'],
                                             u['version'],
                                             u['signature'],
                                             type=u['type'],
                                             resource_type=u['resource_type'])
        instance.save()

        serializer = self.get_read_serializer(instance)
        return Response(serializer.data)
示例#18
0
    def photo(self, request, pk=None):
        file = request.data.get('image')

        u = cloudinary_uploader.upload(file)

        employee = self.queryset.get(id=pk)
        employee.profile_img = CloudinaryResource(
            u['public_id'],
            u['format'],
            u['version'],
            u['signature'],
            type=u['type'],
            resource_type=u['resource_type'])
        employee.save()

        return Response({'url': u['url']}, status=status.HTTP_200_OK)
示例#19
0
    def _rename_file(self, new_name: str, **options):
        # TODO: Cloudinary can't copy files. We dont't want to do it manually
        cloudinary_options = self.get_cloudinary_options()
        cloudinary_options.update(options.get('cloudinary', {}))

        old_name = self.name
        file_field = self.get_file_field()
        folder, basename = posixpath.split(old_name)
        if file_field.resource_type != 'raw':
            # video and image have no extension
            base, ext = posixpath.splitext(new_name)
            new_name = base
        new_name = posixpath.join(folder, new_name)

        try:
            result = uploader.rename(old_name,
                                     new_name,
                                     type=file_field.type,
                                     resource_type=file_field.resource_type,
                                     **cloudinary_options)
        except cloudinary.exceptions.Error as e:
            raise ValidationError(*e.args)

        # fix difference between `public_id` in response
        # and `public_id` in CloudinaryField
        file_format = result.get("format")
        if file_format:
            public_id = result["public_id"]
        else:
            public_id, file_format = posixpath.splitext(result["public_id"])
            file_format = file_format.lstrip('.')

        resource = CloudinaryResource(
            public_id,
            version=str(result["version"]),
            format=file_format,
            type=result["type"],
            resource_type=result["resource_type"],
            metadata=result,
        )
        self.set_file(resource)

        self.basename = helpers.get_filename(new_name)
        self.extension = file_format or ''
        return result
示例#20
0
    def test_uploaded_metadata(self, storage):
        resource = CloudinaryResource(storage.resource.public_id,
                                      type=self.type,
                                      resource_type=self.resource_type)
        file = CloudinaryFieldFile(resource, checksum=self.resource_checksum)

        meta = file.metadata
        assert 'asset_id' in meta
        assert 'public_id' in meta
        assert 'version' in meta
        assert 'version_id' in meta
        assert 'signature' in meta
        assert 'resource_type' in meta
        assert 'created_at' in meta
        assert 'bytes' in meta
        assert 'type' in meta
        assert 'url' in meta
        assert 'secure_url' in meta
 def test_url(self):
     res = CloudinaryResource(metadata=self.uploaded)
     self.assertEqual(res.url, self.uploaded["url"])
 def setUp(self):
     self.res = CloudinaryResource(metadata=self.uploaded)
class TestCloudinaryResource(TestCase):
    mocked_response = http_response_mock('{"breakpoints": [50, 500, 1000]}')
    mocked_breakpoints = [50, 500, 1000]
    expected_transformation = "c_scale,w_auto:breakpoints_50_1000_20_20:json"

    crop_transformation = {'crop': 'crop', 'width': 100}
    crop_transformation_str = 'c_crop,w_100'

    @classmethod
    def setUpClass(cls):
        cloudinary.reset_config()
        cls.uploaded = uploader.upload(TEST_IMAGE,
                                       public_id=TEST_ID,
                                       tags=TEST_TAG)

    @classmethod
    def tearDownClass(cls):
        api.delete_resources_by_tag(TEST_TAG)

    def setUp(self):
        self.res = CloudinaryResource(metadata=self.uploaded)

    def test_empty_class(self):
        """An empty CloudinaryResource"""

        self.shortDescription()
        res = CloudinaryResource()
        self.assertFalse(res, "should be 'False'")
        self.assertEqual(len(res), 0, "should have zero len()")
        self.assertIsNone(res.url, "should have None url")

    def test_validate(self):
        self.assertTrue(self.res.validate())
        self.assertTrue(self.res)
        self.assertGreater(len(self.res), 0)

    def test_get_prep_value(self):
        value = "image/upload/v{version}/{id}.{format}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"])

        self.assertEqual(value, self.res.get_prep_value())

    def test_get_presigned(self):
        value = "image/upload/v{version}/{id}.{format}#{signature}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"],
            signature=self.uploaded["signature"])

        self.assertEqual(value, self.res.get_presigned())

    def test_url(self):
        self.assertEqual(self.res.url, self.uploaded["url"])

    def test_image(self):
        image = self.res.image()
        self.assertIn(' src="{url}'.format(url=self.res.url), image)
        self.assertNotIn('data-src="{url}'.format(url=self.res.url), image)
        image = self.res.image(responsive=True, width="auto", crop="scale")
        self.assertNotIn(
            ' src="{url}'.format(
                url=self.res.build_url(width="auto", crop="scale")), image)
        self.assertIn(
            'data-src="{url}'.format(
                url=self.res.build_url(width="auto", crop="scale")), image)

    @mock.patch('urllib3.request.RequestMethods.request',
                return_value=mocked_response)
    def test_fetch_breakpoints(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource (mocked)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.expected_transformation,
                      get_request_url(mocked_request))

    @mock.patch('urllib3.request.RequestMethods.request',
                return_value=mocked_response)
    def test_fetch_breakpoints_with_transformation(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource with custom transformation (mocked)"""
        srcset = {"transformation": self.crop_transformation}
        actual_breakpoints = self.res._fetch_breakpoints(srcset)

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(
            self.crop_transformation_str + "/" + self.expected_transformation,
            get_request_url(mocked_request))

    def test_fetch_breakpoints_real(self):
        """Should retrieve responsive breakpoints from cloudinary resource (real request)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertIsInstance(actual_breakpoints, list)

        self.assertGreater(len(actual_breakpoints), 0)
示例#24
0
 def test_to_python(self):
     c = CloudinaryField('image')
     res = CloudinaryResource(public_id='sample', format='jpg')
     # Can't compare the objects, so compare url instead
     self.assertEqual(c.to_python('sample.jpg').build_url(), res.build_url())
 def test_to_python(self):
     c = CloudinaryField('image')
     res = CloudinaryResource(public_id=API_TEST_ID, format='jpg')
     # Can't compare the objects, so compare url instead
     self.assertEqual(c.to_python('{}.jpg'.format(API_TEST_ID)).build_url(), res.build_url())
示例#26
0
 def test_uploaded_format(self, storage):
     resource = CloudinaryResource(storage.resource.public_id,
                                   type=self.type,
                                   resource_type=self.resource_type)
     file = CloudinaryFieldFile(resource, checksum=self.resource_checksum)
     assert file.format == 'mp3'
 def test_to_python(self):
     c = CloudinaryField('image')
     res = CloudinaryResource(public_id='sample', format='jpg')
     # Can't compare the objects, so compare url instead
     self.assertEqual(
         c.to_python('sample.jpg').build_url(), res.build_url())
示例#28
0
	def post(self, request):
		form = ConstructorForm(request.POST, request.FILES)
		if form.is_valid():
			im = Image.open("static/img/template-{}.png".format(form.cleaned_data["sex"]))
			is_pattern = form.cleaned_data["is_pattern"]
			print(is_pattern)
			bg = form.cleaned_data["background"]
			if is_pattern:
				imP = Image.open(form.cleaned_data["file"])
				
				width, height = imP.size   # Get dimensions

				left = (width - 1000) / 2
				top = (height - 1000) / 2
				right = (width + 1000) / 2
				bottom = (height + 1000) / 2

				imP = imP.crop((left, top, right, bottom))
			else:
				imP = Image.new("RGBA", size=(1000, 1000), color=(int(bg[1:3], 16), int(bg[3:5], 16), int(bg[5:7], 16), 255))
			
			imP.paste(im, (0, 0), im)
			
			im = imP.copy()

			if not is_pattern and form.cleaned_data["file"]:
				imPR = Image.open(form.cleaned_data["file"])

				ratio = (imPR.size[0] / 250)

				r_imPR = imPR.resize((250, int(imPR.size[1] / ratio)))

				pos = (500 - r_imPR.size[0] // 2, 500 - r_imPR.size[1] // 2)
				im.paste(r_imPR, pos)

			im.save("temp/temp.png")

			resp = cloudinary.uploader.upload('temp/temp.png')
			result = CloudinaryResource(
				public_id=resp['public_id'],
				type=resp['type'],
				resource_type=resp['resource_type'],
				version=resp['version'],
				format=resp['format'],
			)

			str_result = result.get_prep_value()

			if request.FILES:
				resp2 = cloudinary.uploader.upload(File.open(request.FILES["file"], "rb"))
				result2 = CloudinaryResource(
					public_id=resp2['public_id'],
					type=resp2['type'],
					resource_type=resp2['resource_type'],
					version=resp2['version'],
					format=resp2['format'],
				)
				str_result2 = result2.get_prep_value()
			else:
				str_result2 = None


			tshirt = TShirt.objects.create(
				user=request.user,
				name=form.cleaned_data["name"],
				description=form.cleaned_data["description"],
				image=str_result,
				sex=form.cleaned_data["sex"],
				uploaded_image=str_result2,
				background=form.cleaned_data["background"],
				is_pattern=form.cleaned_data["is_pattern"],
			)
			tshirt.topic.set(form.cleaned_data["topic"])
			tshirt.tag.set(form.cleaned_data["tag"])
	


			return redirect('design_view', tshirt_id=tshirt.id)
		else:
			data = {
				"form": form,
			}
			return render(request, "core/constructor.html", context=data)
class TestCloudinaryResource(TestCase):
    mocked_response = http_response_mock('{"breakpoints": [50, 500, 1000]}')
    mocked_breakpoints = [50, 500, 1000]
    expected_transformation = "c_scale,w_auto:breakpoints_50_1000_20_20:json"

    crop_transformation = {'crop': 'crop', 'width': 100}
    crop_transformation_str = 'c_crop,w_100'

    @classmethod
    def setUpClass(cls):
        cloudinary.reset_config()
        cls.uploaded = uploader.upload(TEST_IMAGE, public_id=TEST_ID, tags=TEST_TAG)

    @classmethod
    def tearDownClass(cls):
        cleanup_test_resources_by_tag([(TEST_TAG,)])

    def setUp(self):
        self.res = CloudinaryResource(metadata=self.uploaded)

    def test_empty_class(self):
        """An empty CloudinaryResource"""

        self.shortDescription()
        res = CloudinaryResource()
        self.assertFalse(res, "should be 'False'")
        self.assertEqual(len(res), 0, "should have zero len()")
        self.assertIsNone(res.url, "should have None url")

    def test_validate(self):
        self.assertTrue(self.res.validate())
        self.assertTrue(self.res)
        self.assertGreater(len(self.res), 0)

    def test_get_prep_value(self):
        value = "image/upload/v{version}/{id}.{format}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"])

        self.assertEqual(value, self.res.get_prep_value())

    def test_get_presigned(self):
        value = "image/upload/v{version}/{id}.{format}#{signature}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"],
            signature=self.uploaded["signature"])

        self.assertEqual(value, self.res.get_presigned())

    def test_url(self):
        self.assertEqual(self.res.url, self.uploaded["url"])

    def test_image(self):
        image = self.res.image()
        self.assertIn(' src="{url}'.format(url=self.res.url), image)
        self.assertNotIn('data-src="{url}'.format(url=self.res.url), image)
        image = self.res.image(responsive=True, width="auto", crop="scale")
        self.assertNotIn(' src="{url}'.format(url=self.res.build_url(width="auto", crop="scale")), image)
        self.assertIn('data-src="{url}'.format(url=self.res.build_url(width="auto", crop="scale")), image)

    @mock.patch('urllib3.request.RequestMethods.request', return_value=mocked_response)
    def test_fetch_breakpoints(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource (mocked)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.expected_transformation, get_request_url(mocked_request))

    @mock.patch('urllib3.request.RequestMethods.request', return_value=mocked_response)
    def test_fetch_breakpoints_with_transformation(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource with custom transformation (mocked)"""
        srcset = {"transformation": self.crop_transformation}
        actual_breakpoints = self.res._fetch_breakpoints(srcset)

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.crop_transformation_str + "/" + self.expected_transformation,
                      get_request_url(mocked_request))

    def test_fetch_breakpoints_real(self):
        """Should retrieve responsive breakpoints from cloudinary resource (real request)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertIsInstance(actual_breakpoints, list)

        self.assertGreater(len(actual_breakpoints), 0)
 def test_validate(self):
     res = CloudinaryResource(metadata=self.uploaded)
     self.assertTrue(res.validate())
     self.assertTrue(res)
     self.assertGreater(len(res), 0)
 def test_validate(self):
     res = CloudinaryResource(metadata=self.uploaded)
     self.assertTrue(res.validate())
     self.assertTrue(res)
     self.assertGreater(len(res), 0)
 def setUp(self):
     self.res = CloudinaryResource(metadata=self.uploaded)