How not to create the same dynamic image twice in Python, Django?

I have a view that returns a generated image. I use the view twice: to show the image on a page with some other content, and to show the image in a separate window when the image is clicked. But since it takes quite a long time to generate the image, I would like to somehow avoid the uncertainty in order 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 I generated for the index template by showing it in a separate window and then just forget about the image.

update the 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 . cache.delete(key)

doesn't clear cache for me. Here's a test to demonstrate this:

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

      

+3


source to share


1 answer


Use a cached view :



from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def dynamic_image(request, graph_name):
    ...

      

0


source







All Articles