Django Imagekit覆盖缓存文件名?

2024-09-30 18:25:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图覆盖django imagekit模块中的cachefile_name属性。在

这是我的代码:

class Thumb150x150(ImageSpec):
    processors = [ResizeToFill(150, 150)]
    format = 'JPEG'
    options = {'quality': 90}

    @property
    def cachefile_name(self):
        # simplified for this example
        return "bla/blub/test.jpg"

register.generator('blablub:thumb_150x150', Thumb150x150)

class Avatar(models.Model):
avatar= ProcessedImageField(upload_to=upload_to,
                            processors=[ConvertToRGBA()],
                            format='JPEG',
                            options={'quality': 60})
avatar_thumb = ImageSpecField(source='avatar',
                              id='blablub:thumb_150x150')

当我调试(不覆盖cachefile_name)并查看cachefile_name的返回值时,结果是一个类似“CACHE/blablub/asdlkfjasd09fsaud0”的字符串福建jpg". 我的错误在哪里?在

有什么想法吗?在


Tags: tonameformatclassjpegoptionsjpgupload
2条回答

我认为,正确的方法是设置IMAGEKIT_SPEC_CACHEFILE_NAMER。看看默认名称names.py,它连接在一起settings.IMAGEKIT_CACHEFILE_目录对于文件路径和哈希,您可能应该这样做。在

尽可能地复制这个例子,效果很好。一些建议是:

1)确保在视图中使用的是虚拟人物拇指。文件“bla/blub/测试.jpg“在此之前不会生成。在

2)检查媒体根目录的配置,确保您知道“bla/blub”在哪里/测试.jpg“预计会出现。在

让我举一个类似的例子。我想给我的缩略图唯一的名字,可以预测从原来的文件名。Imagekit的默认方案基于散列来命名缩略图,我猜不出来。而不是这样:

media/12345.jpg
media/CACHE/12345/abcde.jpg

我想要这个:

^{pr2}$

重写IMAGEKIT_SPEC_CACHEFILE_NAMER不起作用,因为我不希望所有缓存的文件都位于“thumbs”目录中,而只是那些从特定模型中的特定字段生成的文件。在

所以我创建了这个ImageSpec子类并注册了它:

class ThumbnailSpec(ImageSpec):
    processors=[Thumbnail(200, 200, Anchor.CENTER, crop=True, upscale=False)]
    format='JPEG'
    options={'quality': 90}

    # put thumbnails into the "photos/thumbs" folder and
    # name them the same as the source file
    @property
    def cachefile_name(self):
        source_filename = getattr(self.source, 'name', None)
        s = "photos/thumbs/" + source_filename
        return s

register.generator('myapp:thumbnail', ThumbnailSpec)

然后在我的模型中这样使用它:

# provide a unique name for each image file
def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    return "%s.%s" % (uuid.uuid4(), ext.lower())

# store the original images in the 'photos/original' directory
photoStorage = FileSystemStorage(
    location=os.path.join(settings.MEDIA_ROOT, 'photos/original'),
    base_url='/photos/original')

class Photo(models.Model):
    image = models.ImageField(storage=photoStorage, upload_to=get_file_path)
    thumb = ImageSpecField(
        source='image',
        id='myapp:thumbnail')

相关问题 更多 >