So i have read the Django-Docs about caching and understood i can cache data per view which is what i want to do. I have a URL like this : www.mysite.com/related_images/{image_id}. which calculates related images for the selected {image_id} and saves them to the disk so they can be accessed by the template. Thing is i don't want those images to stay there forever, but right now my view saves them to the disk without any caching, how can i make sure that by caching the view for a certain period of time, any files created by the view will be deleted when the cache expires ?.
Or if you have a better solution for my problem, I'm open for ideas. Is there a way to inject images from cache into templates without saving them on disk and providing a path for the html explicitly ?
here's a simplified version of the view:
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})
Thanks :)
One solution would be to look at the file metadata for it's last modified date and compare that to a set expiration period.
For example:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.