def get_avatar(context, user, **kwargs): UserModel = get_user_model() request = context.get('request') user_profile = None try: user_profile = user.user_profile except Exception: pass if not isinstance(user, UserModel): image_url = get_avatar_path('M') return generate_url(image_url, **kwargs) if user.is_active or ((request and request.user == user) and (request and request.user.is_authenticated())): if user_profile and user_profile.profile_picture and user_profile.profile_picture.name: image_url = '%s/%s' % (settings.THUMBOR_MEDIA_URL, user_profile.profile_picture.name) else: image_url = get_avatar_path(user_profile.gender if user_profile and user_profile.gender else 'M') elif not user.is_active: image_url = get_avatar_path(user_profile.gender if user_profile and user_profile.gender else 'M') else: image_url = get_avatar_path('M') return generate_url(image_url, **kwargs)
def test_should_apply_alias(self): imp.reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=URL, alias='thumb-square') mock.assert_called_with( image_url=URL, width=300, height=300, filters=['brightness(10)'])
def test_should_pass_args_from_settings_to_crypto(self): imp.reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=self.url) mock.assert_called_with(image_url=self.url, smart=True, fit_in=True)
def test_should_apply_alias(self): imp.reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=URL, alias='thumb-square') mock.assert_called_with(image_url=URL, width=300, height=300, filters=['brightness(10)'])
def __process__(self): queryset = self._get_queryset() title = self.cleaned_data['title'] message = self.cleaned_data['message'] url = self.cleaned_data['url'] icon_url = "https://www.portalgsti.com.br/static/images/favicon-96x96.png" icon_url = generate_url(icon_url, width=60, height=60) per_page = 25 seconds = 0 batch = 3 paginated = paginator.Paginator(queryset, per_page) for index, page in enumerate(paginated.page_range): send_queryset = self._get_queryset() id_list = [item.id for item in paginated.page(page).object_list] send_queryset = send_queryset.filter(id__in=id_list) extra = {'click_action': url, "icon": icon_url} send_push_async.apply_async( args=[send_queryset, title, message, extra], countdown=seconds) if index % batch == 0: seconds += 1 return queryset
def get_file_media_url(self, path, filename): media_url = os.path.join(settings.MEDIA_URL, path, filename) thumbor_media_url = generate_url(media_url, width=getattr( settings, 'MAXIMUM_PC_IMAGE_WIDTH', 300)) return thumbor_media_url
def get(self, request): form = CoreSearchFollowings(request.user, None, request.GET) users_followings = form.process() users_followings = users_followings.get('items') users = [] for u in users_followings: img_url = u.content_object.profile.profile_picture if img_url: img_url = str(settings.THUMBOR_MEDIA_URL) + '/' + str(img_url) elif u.content_object.profile and u.content_object.profile.gender: img_url = settings.AVATAR[u.content_object.profile.gender] else: img_url = settings.AVATAR['M'] thumbnail = generate_url(img_url, width=20, height=20, thumbor_server=settings.THUMBOR_SERVER) user = { 'name': u.content_object.get_full_name(), 'img': thumbnail, 'id': u.content_object.id } users.append(user) context = {'users': users} return self.return_success(request, context)
def get_all_communities(criteria='', items_per_page=10, page=1): if items_per_page > 100: items_per_page = 100 queryset = Community.objects.filter(title__icontains=criteria).only("slug", "title") items_per_page = items_per_page if items_per_page else 6 page = page if page else 1 communities = [] if items_per_page and page: communities = Paginator(queryset, items_per_page) try: communities = communities.page(page) except PageNotAnInteger: communities = communities.page(1) except EmptyPage: communities = [] data = [] for community in communities: data.append({ 'slug': community.slug, 'title': community.title, 'thumb_url': django_thumbor.generate_url( community.image.url, width=16, height=16 ), }) return data
def get_carousel_url(self, obj): return generate_url( obj.get_medium_url(), smart=True, width=CAROUSEL_WIDTH, height=CAROUSEL_HEIGHT, )
def resized_image(self, obj): if obj.image and obj.image.url: url = generate_url(obj.image.url, thumbor_server=settings.THUMBOR_SERVER, width=30) img = "<img src=\"%s\" />" % url return img else: return "No image"
def test_should_return_the_result(self): encrypted_url = 'encrypted-url.jpg' encrypted_url_with_host = 'http://localhost:8888/encrypted-url.jpg' with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(self.url) self.assertEqual(url, encrypted_url_with_host)
def _generate_url(self, width=None, height=None, smart=False, fit_in=False, fill_colour=None, auto_resize=False): image_url = "{}/{}".format(getattr(settings, 'AWS_LOCATION', ''), self.image.name).strip('/') # set the correct orientation if force not to be auto-cropped size = [width, height] if not (self.is_horizontal or fit_in): size.reverse() thumbor_params = { key: value for key, value in zip([ 'width', 'height', ], size) if value } # set default filter to always generate a jpeg image format thumbor_params['filters'] = [ 'format(jpeg)', ] # delete height or width param according photo orientation to auto resize it if auto_resize: thumbor_params.pop('height' if self.is_horizontal else 'width', None) # set auto-fill filter and default colour if fit_in: fill_colour = (fill_colour or config.THUMBNAIL_FILL_COLOUR).strip('#') filters = thumbor_params.get('filters', []) filters.append('fill({})'.format(fill_colour)) thumbor_params.update({'filters': filters}) url = generate_url(image_url, smart=smart, fit_in=fit_in, **thumbor_params) # remove unsave string from thumbor url if getattr(settings, 'THUMBOR_URL_REMOVE_UNSAFE', False): url = url.replace('/unsafe/', '/') # add prefix to media url prefix = getattr(settings, 'THUMBOR_MEDIA_URL_PREFIX', '') if prefix: media_url = getattr(settings, 'THUMBOR_MEDIA_URL', '') url = url.replace("/{}/".format(media_url), "/{}/{}/".format(prefix, media_url)) return url
def test_should_return_the_result(self): encrypted_url = 'encrypted-url.jpg' encrypted_url_with_host = 'http://localhost:8888/encrypted-url.jpg' with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(URL) self.assertEqual(url, encrypted_url_with_host)
def test_should_remove_ending_slash_from_custom_server(self): encrypted_url = 'encrypted-url.jpg' custom_server = 'http://localhost:8888/foo/' encrypted_url_with_host = '{0}{1}'.format(custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(URL, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def render(self, name, value, attrs=None): if not attrs: attrs = {} if value: new_attrs = get_attrs(value, name) # fix to make it work with thumbor instead of easy_thumbnails if hasattr(value, 'url'): new_attrs['data-thumbnail-url'] = generate_url(value.url, width=300) attrs.update(new_attrs) return super(ImageThumbnailWidget, self).render(name, value, attrs)
def test_should_pass_empty_url(self): encrypted_url = "" custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format( custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = "" url = generate_url(mock.return_value, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def serialize_user(self, user): return { 'id': user.id, 'name': user.get_full_name(), 'img': django_thumbor.generate_url(user.user_profile.avatar_url, width=16, height=16) }
def test_should_return_the_result_with_a_custom_server(self): encrypted_url = 'encrypted-url.jpg' custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format( custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(URL, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def test_should_return_the_result_with_a_custom_server(self): encrypted_url = 'encrypted-url.jpg' custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format(custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(self.url, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def test_should_remove_ending_slash_from_custom_server(self): encrypted_url = 'encrypted-url.jpg' custom_server = 'http://localhost:8888/foo/' encrypted_url_with_host = '{0}{1}'.format( custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = encrypted_url url = generate_url(self.url, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def test_should_pass_empty_url(self): encrypted_url = "" custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format(custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = "" url = generate_url(mock.return_value, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def test_should_pass_the_image_with_url_param(self): image_mock = MockImageField() encrypted_url = image_mock.url custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format( custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = image_mock.url url = generate_url(image_mock, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def get_thumbor_thumbnail_url(image, **kwargs): storage = image.storage thumbor_server = settings.THUMBOR_SERVER_EXTERNAL url = quote(image.url) if hasattr(storage, "key"): try: url = storage.key(image.name) except NotImplementedError: pass else: thumbor_server = settings.THUMBOR_SERVER return generate_url(url, thumbor_server=thumbor_server, **kwargs)
def test_should_pass_the_image_with_url_param(self): image_mock = MockImageField() encrypted_url = image_mock.url custom_server = 'http://localhost:8888/foo' encrypted_url_with_host = '{0}/{1}'.format(custom_server, encrypted_url) with patch('django_thumbor.crypto.generate') as mock: mock.return_value = image_mock.url url = generate_url(image_mock, thumbor_server=custom_server) self.assertEqual(url, encrypted_url_with_host)
def render(self, name, value, attrs=None): if not attrs: attrs = {} if value: new_attrs = get_attrs(value, name) # fix to make it work with thumbor instead of easy_thumbnails if hasattr(value, 'url'): # Hack to get rid of the signature which we don't need # TODO: find a better way url = value.url.split('?')[0] new_attrs['data-thumbnail-url'] = generate_url(url, width=400) attrs.update(new_attrs) return super(ImageThumbnailWidget, self).render(name, value, attrs)
def get(self, request, user_id, size=40): if not user_id: raise Http404() if int(size) > 100: raise Http404('Invalid size') try: user = User.objects.get(id=user_id, usertype=User.PERSON, is_active=True) image_url = django_thumbor.generate_url( user.user_profile.avatar_url, width=size) return redirect(to=image_url) except Exception as e: raise Http404('Not found {}', e)
def replace_mobile_thubor(text): # return regex_thumbor_mobile.sub('/{}x0/'.format(settings.MAXIMUM_MOBILE_IMAGE_WIDTH), text) # return generate_url() matches = regex_thumbor_mobile.findall(text) if not matches or len(matches) == 0: return text for match_original in matches: match = list(copy.copy(match_original)) if len(match) < 4: continue text = str(text).replace( '/'.join(match_original), generate_url(match[3], width=settings.MAXIMUM_MOBILE_IMAGE_WIDTH)) return text
def post(self, *args, **kwargs): image = self.request.FILES['photo'] image.name = self.sanitize_file_name(image.name) image_file = ImageMediaFile.objects.create(photo=image) filters = { 'width': 300, } url = generate_url(image_url=image_file.photo.url, **filters) data = { 'success': True, 'src': url, 'id': image_file.pk, 'width': image_file.photo.width, 'height': image_file.photo.height, } response = json.dumps(data) return HttpResponse(response, content_type="application/json")
def get_user_communities_list_from_queryset(queryset, author, width=20, height=20, id_field='id'): communities = [] for community in queryset: img_url = str(settings.THUMBOR_MEDIA_URL) + '/' + str(community.image) c = dict() c['id'] = getattr(community, id_field) c['name'] = community.title c['image'] = generate_url(img_url, width=width, height=height, thumbor_server=settings.THUMBOR_SERVER) communities.append(c) return communities
def get_sidebar_url(self, obj): return generate_url(obj.get_medium_url(), smart=True, width=SIDEBAR_WIDTH, height=SIDEBAR_HEIGHT)
def test_should_raise_with_nonexistent_alias(self): imp.reload(conf) with self.assertRaises(RuntimeError): generate_url(image_url=URL, alias='thumb-square')
def test_should_pass_url_arg_to_crypto(self): with patch('django_thumbor.crypto.generate') as mock: generate_url(URL) mock.assert_called_with(image_url=URL)
def assertPassesArgsToCrypto(self, *args, **kwargs): with patch('django_thumbor.crypto.generate') as mock: generate_url(*args, **kwargs) mock.assert_called_with(*args, **kwargs)
def image_thumb(self, obj): if obj.image: return u'<img width="60px" height="60px" src="{0}" />'.format( generate_url(obj.image.url, width=60, height=60)) return _(u'No Image')
def thumbor_url(image_url, **kwargs): return generate_url(image_url=image_url, **dict(conf.THUMBOR_ARGUMENTS, **kwargs))
def test_should_allow_overriding_args_from_settings(self): imp.reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=URL, smart=False) mock.assert_called_with(image_url=URL, smart=False)
def generate_url_with_dimensions(url, dimensions): return "src=\"%s\"" % generate_url( url, height=dimensions['height'], width=dimensions['width'])
def thumborized_picture(self, user): return generate_url( user.profile.profile_picture.url, width=50, height=50 ) if user.profile and user.profile.profile_picture else None
def test_should_allow_overriding_args_from_settings(self): reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=self.url, smart=False) mock.assert_called_with(image_url=self.url, smart=False)
def get_carousel_url(self, obj): return generate_url(obj.get_medium_url(), smart=True, width=CAROUSEL_WIDTH, height=CAROUSEL_HEIGHT)
def thumbor_url(image_url, **kwargs): filters = kwargs.get('filters') if filters and isinstance(filters, STRING_TYPES): kwargs['filters'] = _parse_filters(filters) return generate_url(image_url=image_url, **kwargs)
def assertURLEquals(self, original, expected, **kwargs): with patch('django_thumbor.crypto.generate') as mock: generate_url(original, **kwargs) mock.assert_called_with(image_url=expected)
def test_should_pass_url_arg_to_crypto(self): with patch('django_thumbor.crypto.generate') as mock: generate_url(self.url) mock.assert_called_with(image_url=self.url)
def test_should_pass_args_from_settings_to_crypto(self): reload(conf) with patch('django_thumbor.crypto.generate') as mock: generate_url(image_url=self.url) mock.assert_called_with( image_url=self.url, smart=True, fit_in=True)
def thumborized_picture(self, profile): return generate_url(profile.profile_picture.url, width=30, height=30) if profile.profile_picture else None
def assertURLEquals(self, original, expected): with patch('django_thumbor.crypto.generate') as mock: generate_url(original) mock.assert_called_with(image_url=expected)
def _get_thumbor_file_url(self): return generate_url(width=settings.THUMBOR_IMAGE_WIDTH, image_url=self.file.url)