浏览器中的图像缓存 - app-engine-patch 应用程序

4
我有一个小问题,在我的应用程序引擎中缓存图像时。虽然我发送了last-modified、expires和cache-control头信息,但图像仍然每次从服务器加载。以下是代码的头部分:
response['Content-Type'] = 'image/jpg'
response['Last-Modified'] = current_time.strftime('%a, %d %b %Y %H:%M:%S GMT')
response['Expires'] = current_time + timedelta(days=30)
response['Cache-Control'] = 'public, max-age=2592000'
1个回答

7

这是一个我修复dpaste中复制问题的示例代码,请点击此处查看

def view_image(request, key):
  data = memcache.get(key)  
  if data is not None:  
    if(request.META.get('HTTP_IF_MODIFIED_SINCE') >= data['Last-Modified']):  
      data.status_code = 304  
    return data  
  else:  
    image_content_blob = #some code to get the image from the data store  
    current_time = datetime.utcnow()
    response = HttpResponse()
    last_modified = current_time - timedelta(days=1)
    response['Content-Type'] = 'image/jpg'
    response['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
    response['Expires'] = current_time + timedelta(days=30)
    response['Cache-Control']  = 'public, max-age=315360000'
    response['Date']           = current_time
    response.content = image_content_blob

    memcache.add(image_key, response, 86400)
    return response

1
首先要记住的是,如果你像我一样喜欢Django并且有一个自定义中间件,那么每次请求图像时都会执行该中间件。这可能会(并且会)增加开销。其次,在上面的示例中,我已经将内容类型硬编码为'image/jpg',这会导致在Safari和IE中仅显示图像时出现一些问题(如果它在HTML页面中则正常工作)。 - Ilian Iliev
AppEngine上的响应不允许使用“日期”头信息。请参考http://code.google.com/appengine/docs/python/tools/webapp/responseclass.html#Disallowed_HTTP_Response_Headers。 - Piotr Duda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接