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

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
于 2019-08-28T20:26:52.103 に答える