【问题标题】:Python-Django Caching imagesPython-Django 缓存图像
【发布时间】:2016-02-09 23:51:53
【问题描述】:

所以我已经阅读了关于缓存的 Django-Docs 并了解我可以缓存每个视图的数据,这是我想要做的。我有一个这样的网址: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})

谢谢:)

【问题讨论】:

    标签: python django caching django-caching


    【解决方案1】:

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

    例如:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2014-12-27
      • 1970-01-01
      • 2013-10-24
      • 2014-03-17
      相关资源
      最近更新 更多