python - Django: Client-side caching using etags -
more questions work through lightweight django. in chapter 2, book talks client-side caching using django.views.decorators.http.etag
decorator. wrote the following view:
import hashlib import pil.imagedraw imagedraw django.core.cache import cache django.http import httpresponse, httpresponsebadrequest django import forms io import bytesio pil import image django.views.decorators.http import etag class imageform(forms.form): """form vlaidate requested placeholder image.""" height = forms.integerfield(min_value=1, max_value=2000) width = forms.integerfield(min_value=1, max_value=2000) def generate(self, image_format="png"): """generate image of given format , return raw bytes""" height = self.cleaned_data["height"] width = self.cleaned_data["width"] image = image.new("rgb", (width, height)) # color optional # create key cached content cache_key = "{} x {} x {}".format(height, width, image_format) # add text around image being served draw = imagedraw.draw(image) text = "{} x {}".format(width, height) textwidth, textheight = draw.textsize(text) # text size of text if textwidth < width , textheight < height: texttop = (height - textheight) // 2 textleft = (width - textwidth) // 2 draw.text((textleft, texttop), text, fill=(255, 255, 255)) content = bytesio() image.save(content, image_format) content.seek(0) cache.set(cache_key, content, 60 * 60) return(content) def etag_placeholder(request, width, height): content_to_hash = "placeholder: {} x {}".format(width, height) return(hashlib.sha1(content_to_hash.encode("utf-8")).hexdigest()) @etag(etag_placeholder) def placeholder(request, width, height): form = imageform({'height': height, "width": width}) if form.is_valid(): image = form.generate() return(httpresponse(image, content_type="image/png")) else: return(httpresponsebadrequest("incorrect image dimensions requested."))
however, view refuses cache, , continue 200 responses -- expecting see 304s. there setting missing?
Comments
Post a Comment