【发布时间】: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