========= config file begin =============== NAME = u'captcha' LETTERS = u'1234567890' #ABCDEFGHIJKLMNOPQRSTUVWXYZ' COLOURS = ( (203,61,27), (39,151,58), (0,139,120), (0,151,220), (1,53,146), (129,30,104), (183,1,111), (230,0,58), (0,0,0), ) FONTS = ( u'ariblk.ttf', u'comic.ttf', u'georgia.ttf', u'impact.ttf', u'tahomabd.ttf', ) FONT_SIZE = 12 LENGTH = 5 ========= config file end =============== ========= widgets file begin =============== class CaptchaWidget(Widget): def render(self, name, value, attrs = None): '''验证码HTML内容''' attrs = self.build_attrs(attrs, name=name) output = [u''] output.append(u'' % flatatt(attrs)) return mark_safe(u'
'.join(output)) ========= widgets file end =============== ========= models file begin =============== class Captcha: '''验证码''' def __init__(self, request, *args, **kwargs): self.request = request @staticmethod def text(): return ''.join([random.choice(captcha.LETTERS) for i in range(captcha.LENGTH)]) def get(self): return self.request.session.get(captcha.NAME, '') def destroy(self): self.request.session[captcha.NAME] = '' def create(self): self.request.session[captcha.NAME] = self.text() ========= models file end =============== ========= views file begin =============== def image(request): """验证码图片""" captcha_text = Captcha(request).get() response = HttpResponse() if captcha_text: image = Image.new("RGBA", (captcha.LENGTH * captcha.FONT_SIZE - 26, captcha.FONT_SIZE), (0,0,0,0)) canvas = ImageDraw.Draw(image) for i in range(0, len(captcha_text)): # font = ImageFont.truetype(choice(captcha.FONTS), captcha.FONT_SIZE) # canvas.text((captcha.FONT_SIZE*i+2, -4), captcha_text[i], font = font, fill = choice(captcha.COLOURS)) horizon = 1; verticality = -1 if i>0: horizon = (captcha.FONT_SIZE - 5) * i if i%2 == 0: verticality = 2 canvas.text((horizon, verticality), captcha_text[i], fill = choice(captcha.COLOURS)) out = StringIO() image.save(out, "PNG") out.seek(0) response['Content-Type'] = 'image/png' response.write(out.read()) return response ========= views file end ===============