【问题标题】:How not to generate the same dynamic image twice in Python, Django?如何不在 Python、Django 中生成两次相同的动态图像?
【发布时间】:2015-03-09 17:47:01
【问题描述】:

我有一个返回生成图像的视图。我使用了两次视图:在页面上显示带有其他内容的图像,并在单击图像时在单独的窗口中显示图像。但是由于图像的生成需要很长时间,我想以某种方式逃避重复自己的需要。

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>

我希望我可以重用为索引模板生成的图像,通过在单独的窗口中显示它然后忘记图像。

upd按照建议添加了cache_page

@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) 没有为我清除缓存。这是演示它的测试:

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

【问题讨论】:

  • 不想再点击生成图片?
  • 是的。而且我也不想将它存储在服务器上。但如果这是唯一的选择,我会的。
  • 是同一张图片吗?一样大吗?有多种方法可以做到这一点。一,你可以使用 JS 而不是发送另一个服务器请求。您还可以查看 Django 的缓存框架并在完成后使缓存无效:docs.djangoproject.com/en/1.7/topics/cache 还有其他方法,但我会从这里开始,看看这是否是您需要的。
  • 缓存是我所需要的。
  • 太棒了!祝你好运! :)

标签: python django django-templates django-views


【解决方案1】:

使用cached view

from django.views.decorators.cache import cache_page

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

【讨论】:

  • 这看起来很酷,而且比我想象的要简单得多。我如何手动uncache_page(不是在 15 分钟后)?
  • 您可以使用get_cache_key() 方法获取您查看的密钥。可以使用cache.delete(key) 删除缓存的视图结果。请参阅文档:docs.djangoproject.com/en/1.7/ref/utils/…
  • 看这个问题的答案:stackoverflow.com/questions/2268417/…
  • 要检查缓存视图的值,您应该使用cache.get(key) 而不是get_cache_key(request)
猜你喜欢
  • 2020-02-21
  • 2022-08-16
  • 2011-03-31
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 2021-08-24
相关资源
最近更新 更多