Пример #1
0
Файл: models.py Проект: ria4/tln
 def _get_SIZE_size(self, size):
     # this should never be called for a non-placeholder size
     photosize = PhotoSizeCache().sizes.get(size)
     if not self.size_exists(photosize):
         self.create_size(photosize)
     return Image.open(
         self.photo.image.storage.open(self._get_SIZE_filename(size))).size
Пример #2
0
    def setUpTestData(cls):
        super(APITestCase, cls).setUpTestData()

        # Editor
        cls.editor = get_user_model().objects.create(
            username="******",
            email="*****@*****.**",
            is_superuser=True,
            is_staff=True)
        cls.editor.set_password("password")
        cls.editor.save()

        # Prep
        Site.objects.all().delete()
        Site.objects.create(id=1, domain="site.example.com")
        ModelBase.objects.all().delete()

        # Objects for this test
        cls.obj1 = TestModel(title="title1")
        cls.obj1.save()
        cls.obj2 = TestModel(title="title2", state="published")
        cls.obj2.save()
        cls.obj2.sites = Site.objects.all()
        cls.obj2.save()

        cls.image = Image.objects.create(title=IMAGE_PATH)
        cls.image.image.save(os.path.basename(IMAGE_PATH),
                             ContentFile(open(IMAGE_PATH, "rb").read()))
        cls.mbi1 = ModelBaseImage.objects.create(modelbase=cls.obj1,
                                                 image=cls.image)
        cls.mbi2 = ModelBaseImage.objects.create(modelbase=cls.obj2,
                                                 image=cls.image)

        call_command("load_photosizes")
        PhotoSizeCache().reset()
Пример #3
0
Файл: models.py Проект: ria4/tln
    def create_size(self, photosize):
        if not photosize.name.endswith('_placeholder'):
            self.photo.create_size(photosize)
            return

        if self.size_exists(photosize):
            return

        namesplit = photosize.name.split('_')
        display_size, placeholder = '_'.join(namesplit[:-1]), namesplit[-1]

        photosize_display = PhotoSizeCache().sizes.get(display_size)
        if (photosize_display is None) or (placeholder != 'placeholder'):
            raise Exception('Invalid PhotoSize name!')

        if not self.photo.size_exists(photosize_display):
            self.photo.create_size(photosize_display)

        i_relpath = '/'.join([
            self.photo.cache_url(),
            filepath_to_uri(self.photo._get_filename_for_size(display_size))
        ])
        o_relpath = '/'.join([
            self.photo.cache_url(),
            filepath_to_uri(self._get_filename_for_size(photosize.name))
        ])
        i_path = os.path.abspath(i_relpath[1:])
        o_path = os.path.abspath(o_relpath[1:])
        cmd = '/usr/bin/npx sqip -o {} -m {} -n {} -b {} {}'.format( \
                    o_path,
                    self.placeholder_primitive_mode,
                    self.placeholder_primitive_number,
                    self.placeholder_blur,
                    i_path)
        #cmd = '/usr/bin/npx sqip -i {} -o {} -w {} -m {} -n {} -b {}'.format( \
        #            i_path,
        #            o_path,
        #            self.placeholder_width,
        #            self.placeholder_primitive_mode,
        #            self.placeholder_primitive_number,
        #            self.placeholder_blur)
        try:
            subprocess.run(cmd.split(), timeout=180, check=True)
        except subprocess.CalledProcessError:
            logger.error(
                'Creating a placeholder for %s returned a non-zero exit status!'
                % i_path)
        except subprocess.TimeoutExpired:
            logger.error('Creating a placeholder for %s timed out!' % i_path)

        try:
            tree = ET.parse(o_path)
            root = tree.getroot()
            dimensions = root.attrib['viewBox'].split()[2:4]
            root.attrib['width'] = dimensions[0] + 'px'
            root.attrib['height'] = dimensions[1] + 'px'
            tree.write(open(o_path, 'wb'))
        except Exception:
            logger.error('Writing placeholder dimensions for %s failed!' %
                         i_path)
Пример #4
0
Файл: models.py Проект: ria4/tln
 def _get_SIZE_url(self, size):
     # this should never be called for a non-placeholder size
     photosize = PhotoSizeCache().sizes.get(size)
     if not self.size_exists(photosize):
         self.create_size(photosize)
     return '/'.join([
         self.photo.cache_url(),
         filepath_to_uri(self._get_filename_for_size(photosize.name))
     ])
Пример #5
0
    def setUpTestData(cls):
        super(ModelBaseTestCase, cls).setUpTestData()
        cls.web_site = Site.objects.all().first()
        cls.mobile_site = Site.objects.all().last()
        call_command("load_photosizes")
        PhotoSizeCache().reset()

        # Clear media root
        rmtree(settings.MEDIA_ROOT)
Пример #6
0
Файл: models.py Проект: ria4/tln
def init_size_method_map_custom():
    global size_method_map_custom
    for size in PhotoSizeCache().sizes.keys():
        if size.endswith('_placeholder'):
            size_method_map_custom['get_%s_size' % size] = \
                {'base_name': '_get_SIZE_size', 'size': size}
            size_method_map_custom['get_%s_url' % size] = \
                {'base_name': '_get_SIZE_url', 'size': size}
            size_method_map_custom['get_%s_filename' % size] = \
                {'base_name': '_get_SIZE_filename', 'size': size}
Пример #7
0
    def setUpTestData(cls):
        super(ViewsTestCase, cls).setUpTestData()

        cls.obj = ModelBase.objects.create(title="title1")
        cls.obj.sites = Site.objects.all()
        cls.obj.save()
        cls.obj.publish()

        call_command("load_photosizes")
        PhotoSizeCache().reset()
Пример #8
0
def _render_photo(photo, params):
    sizes = PhotoSizeCache().sizes
    size = 'thumbnail'
    rel = None
    for param in params:
        if param in sizes.keys():
            size = param
            params.remove(param)
    if params:
        rel = params[0]

    thumbnail_url = getattr(photo, 'get_%s_url' % size)()

    if photo.caption:
        caption = '<span class="caption">%s</span>' % photo.caption
    else:
        caption = ''

    display_size = sizes['display']
    im = Image.open(photo.image.path)
    if im.size[0] > display_size.size[0] or im.size[1] > display_size.size[1]:
        full_url = photo.image.url
        full_specs = '%sx%s' % im.size
        display_url = photo.get_display_url()
    else:
        full_url = photo.get_display_url()
        display_url = full_specs = ''

    kw = {
        'display_url': display_url,
        'full_url': full_url,
        'thumbnail_url': thumbnail_url,
        'title': photo.title,
        'full_specs': full_specs,
        'rel': rel,
        'class': '',
        'caption': caption,
    }
    tag = PHOTO_TAG % kw
    return strip_spaces_between_tags(tag)
Пример #9
0
 def _links(self, obj):
     s = """<a href="%(url)s">%(url)s</a>
         <br />
         <a href="#"
            onclick="django.jQuery('#jmbo-image-cl-links').toggle(); return false;">
             %(label)s
         </a>
         <ul id="jmbo-image-cl-links" style="display: none;">
         """ % {
         "url": obj.image.url,
         "label": _("More / less")
     }
     for name in sorted(PhotoSizeCache().sizes.keys()):
         s += """<li><a href="%(url)s">%(url)s</a></li>""" % \
             {"url": obj._get_SIZE_url(name)}
     s += "</ul>"
     return s
Пример #10
0
 def test(self):
     cache = PhotoSizeCache()
     self.assertEqual(cache.sizes['test'], self.s)
Пример #11
0
Файл: models.py Проект: ria4/tln
 def _get_SIZE_filename(self, size):
     # this should never be called for a non-placeholder size
     photosize = PhotoSizeCache().sizes.get(size)
     return smart_str(
         os.path.join(self.photo.cache_path(),
                      self._get_filename_for_size(photosize.name)))
Пример #12
0
Файл: models.py Проект: ria4/tln
 def clear_cache_placeholder(self):
     cache = PhotoSizeCache()
     for photosize in cache.sizes.values():
         if photosize.name.endswith('_placeholder'):
             self.remove_size_placeholder(photosize, False)
Пример #13
0
def create_missing_vhigh_placeholders(gallery_slug):

    gallery = Gallery.objects.get(slug=gallery_slug)

    photocustoms = []
    for p in gallery.photos.all().order_by('id'):
        photocustoms.append(PhotoCustom.objects.get(photo_id=p.id))
    n = len(photocustoms)

    print('Found %d photos in gallery "%s"\n' % (n, gallery.title))

    for i, pc in enumerate(photocustoms):

        photosize = PhotoSizeCache().sizes.get('vhigh_display_placeholder')
        if pc.size_exists(photosize):
            print('Placeholder already exists for "%s" at %s' %
                  (pc.photo.title,
                   pc._get_SIZE_url('vhigh_display_placeholder')))
            continue

        display_size = 'vhigh_display'
        photosize_display = PhotoSizeCache().sizes.get(display_size)

        if not pc.photo.size_exists(photosize_display):
            pc.photo.create_size(photosize_display)
            print('Created %s' % pc.photo._get_filename_for_size(display_size))

        i_relpath = '/'.join([
            pc.photo.cache_url(),
            filepath_to_uri(pc.photo._get_filename_for_size(display_size))
        ])
        o_relpath = '/'.join([
            pc.photo.cache_url(),
            filepath_to_uri(pc._get_filename_for_size(photosize.name))
        ])
        i_path = os.path.abspath(i_relpath[1:])
        o_path = os.path.abspath(o_relpath[1:])
        cmd = '/usr/bin/npx sqip -o {} -m {} -n {} -b {} {}'.format( \
                    o_path,
                    self.placeholder_primitive_mode,
                    self.placeholder_primitive_number,
                    self.placeholder_blur,
                    i_path)
        #cmd = '/usr/bin/npx sqip -i {} -o {} -w {} -m {} -n {} -b {}'.format( \
        #            i_path,
        #            o_path,
        #            pc.placeholder_width,
        #            pc.placeholder_primitive_mode,
        #            pc.placeholder_primitive_number,
        #            pc.placeholder_blur)
        try:
            subprocess.run(cmd.split(), timeout=180, check=True)
            print('Created a placeholder for photo "%s" (%d / %d)' %
                  (pc.photo.title, i + 1, n))
        except subprocess.CalledProcessError:
            print(
                'Creating a placeholder for %s returned a non-zero exit status!'
                % i_path)
            sys.exit()
        except subprocess.TimeoutExpired:
            print('Creating a placeholder for %s timed out!' % i_path)
            sys.exit()

        try:
            tree = ET.parse(o_path)
            root = tree.getroot()
            dimensions = root.attrib['viewBox'].split()[2:4]
            root.attrib['width'] = dimensions[0] + 'px'
            root.attrib['height'] = dimensions[1] + 'px'
            tree.write(open(o_path, 'wb'))
            print('Updated placeholder SVG dimensions')
        except Exception:
            print('Writing placeholder dimensions for %s failed!' % i_path)
        print()