Lightweight Django。在第2章中,本书讨论了使用django.views.decorators.http.etag
装饰器进行客户端缓存。我写了以下观点:
import hashlib
import PIL.ImageDraw as ImageDraw
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseBadRequest
from django import forms
from io import BytesIO
from PIL import Image
from django.views.decorators.http import etag
class ImageForm(forms.Form):
"""Form to vlaidate the 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 an image of the given format and return raw bytes"""
height = self.cleaned_data["height"]
width = self.cleaned_data["width"]
image = Image.new("RGB", (width, height)) # color is optional
# create the key for the cached content
cache_key = "{} x {} x {}".format(height, width, image_format)
# add text around the image being served up
draw = ImageDraw.Draw(image)
text = "{} x {}".format(width, height)
textwidth, textheight = draw.textsize(text) # get the text size of the text
if textwidth < width and 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."))
然而,这个视图拒绝缓存,我继续得到200个响应 - 我期待看到304。有没有我错过的环境?