2

所以我已经阅读了关于缓存的 Django-Docs 并理解我可以缓存每个视图的数据,这是我想要做的。我有一个这样的 URL:www.mysite.com/related_images/{image_id}。 它计算所选{image_id}的相关图像并将它们保存到磁盘,以便模板可以访问它们。事情是我不希望这些图像永远留在那里,但是现在我的视图将它们保存到磁盘而不进行任何缓存,我如何确保通过缓存视图一段时间来确保由缓存过期时视图将被删除?

或者,如果您对我的问题有更好的解决方案,我愿意提供想法。有没有办法将缓存中的图像注入模板而不将它们保存在磁盘上并明确提供 html 的路径?

这是视图的简化版本:

def related_image(request, pk):

    original = get_object_or_404(Image, pk=pk)
    images = original.get_previous_views()
    for im in images:
        path = '/some/dir/'+str(im.id)+'.jpg'
        calculated_image = calculate(im,original)
        file = open(path)
        file.write(calculated_image)
        im.file_path = path

    return render_to_response('app/related_image.html', {'images': images})

谢谢 :)

4

1 回答 1

0

一种解决方案是查看文件元数据的最后修改日期,并将其与设定的有效期进行比较。

例如:

import os

expiration_seconds = 3600
last_modified_time = os.path.getmtime(file_path)  # i.e. 1223995325.0
# that returns a float with the time of last modification since epoch, 
# so there's some logic to do to determine time passed since then.

if time_since_last_modified >= expiration_seconds:
    # delete the file
    os.remove(file_path)
    # then do your logic to get the file again
于 2019-08-28T20:26:52.103 回答