3

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
Sashko Lykhenko
  • 1,554
  • 4
  • 20
  • 36

1 Answers1

0

Use the cached view:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def dynamic_image(request, graph_name):
    ...
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • This looks cool and way more simple than I thought. And how do I `uncache_page` manualy (not after 15 minutes)? – Sashko Lykhenko Jan 12 '15 at 01:54
  • You can get the key for you view using `get_cache_key()` method. Cached view result can be deleted with `cache.delete(key)`. See the docs: https://docs.djangoproject.com/en/1.7/ref/utils/#django.utils.cache.get_cache_key – catavaran Jan 12 '15 at 02:04
  • Look at the answer for this question: http://stackoverflow.com/questions/2268417/expire-a-view-cache-in-django – catavaran Jan 12 '15 at 02:05
  • To check the value of the cached view you should use `cache.get(key)` instead of `get_cache_key(request)`. – catavaran Jan 12 '15 at 21:30