I have a view that returns a generated image. I use the view twice: to show an image on page with some other stuff and to show the image in separate window when clicking on the image. But since generation of an image takes quite a while I would like to somehow escape the nessecity to repeat myself.
views.py
# named 'dynamic-image' in urls.py
def dynamic_image(request, graph_name):
# generate the image (always the same for our case)
return HttpResponse(image, content_type="image/svg+xml")
def index(request):
template_name = 'graphs/index.html'
...
return render(request,template_name,{})
index.html
<a href = "{% url 'dynamic-image' simplified_cell_states_graph %}">
<img src="{% url 'dynamic-image' simplified_cell_states_graph %}" alt="img3">
</a>
I wish I could reuse the image, generated for index template, by showing it in a separate window and then just forget about the image.
upd added cache_page as suggested
@cache_page(60 * 15)
def dynamic_image(request, graph_name):
# generate the image (always the same for our case)
return HttpResponse(image, content_type="image/svg+xml")
upd How to uncache page? cache.delete(key)
does not clear cache for me. Here is the test demonstrating it:
from django.utils.cache import get_cache_key
from django.core.cache import cache
def test_cache_invalidation_with_cache(self):
self.factory = RequestFactory()
url = reverse('dynamic-image', args=('simplified_cell_states_graph',))
request = self.factory.get(url)
response = self.client.get(url)
cache_key = get_cache_key(request)
self.assertFalse(cache_key == None) #key found
cache.delete(cache_key) # but no deletion
cache_key = get_cache_key(request)
self.assertEquals(cache_key, None) # fails here