views:

339

answers:

1

Hi,

I have a little problem with caching the images in the browser for my app-engine aplication I`m sending last-modified, expires and cache-control headers but image is loaded from the server every time. Here is the header part of the code:

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'

Any ideas?

+4  A: 

Here is an example code for my fix copy in dpaste here

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
Ilian Iliev
First have in mind the if you Django like me and have a custom middleware that middleware is executed every time when an image is requested. This can(and will) raise you overhead.And second in the example above I have hardcoded the content type to 'image/jpg' which causes some problems in displaying only the image(works fine if it is in HTML page) in Safari and IE.
Ilian Iliev