コード例 #1
0
def extract_photo(request, archive_file, photo, album):
    # zipfile and tarfile are inconsistent
    if isinstance(photo, ZipInfo):
        photo_filename = photo.filename
        extract_file = archive_file.open
    elif isinstance(photo, tarfile.TarInfo):
        photo_filename = photo.name
        extract_file = archive_file.extractfile
    else:
        raise TypeError("'photo' must be a ZipInfo or TarInfo object.")

    # Ignore directories
    if not os.path.basename(photo_filename):
        return

    # Generate unique filename
    num = album.photo_set.count()
    filename, extension = os.path.splitext(photo_filename)
    new_filename = str(num).zfill(4) + extension

    photo_obj = Photo()
    photo_obj.album = album
    try:
        with extract_file(photo) as f:
            photo_obj.file.save(new_filename, File(f))

        if not save_photo(photo_obj):
            messages.add_message(request, messages.WARNING,
                                 _("{} is duplicate.").format(photo_filename))
    except (OSError, AttributeError, UnidentifiedImageError):
        messages.add_message(request, messages.WARNING,
                             _("Ignoring {}").format(photo_filename))
        if photo_obj.file.path:
            os.remove(photo_obj.file.path)
        photo_obj.delete()
コード例 #2
0
    def create_photo(self, album):
        photo = Photo()

        photo.album = album

        name = _generate_title()

        igen = IconGenerator(5, 5)  # 5x5 blocks
        icon = igen.generate(
            name,
            480,
            480,
            padding=(10, 10, 10, 10),
            output_format="jpeg",
        )  # 620x620 pixels, with 10 pixels padding on each side
        photo.file.save(f"{name}.jpeg", ContentFile(icon))

        photo.save()