利用Pillow,几行代码实现的最简单的Django页面验证码功能

验证码本质上就是生成带有文字的图片,如果考虑到防止破解自然会涉及到许多复杂的算法,用以防止从图片中容易地识别出文字,作为一个简单的例子,以下就是利用Python的第三方图形处理模块Pillow来实现的一个简单的验证码功能:

首先,在accounts.views中定义一个生成验证码的函数:

from PIL import Image, ImageDraw, ImageFontfrom django.http.response import HttpResponsefrom appboard.settings import BASE_DIRimport cStringIO, string, os, randomdef captcha(request):'''Captcha'''image = Image.new('RGB', (147, 49), color = (255, 255, 255)) # model, size, background colorfont_file = os.path.join(BASE_DIR, 'static/fonts/ARIAL.TTF') # choose a font filefont = ImageFont.truetype(font_file, 47) # the font objectdraw = ImageDraw.Draw(image)rand_str = ''.join(random.sample(string.letters + string.digits, 4)) # The random stringdraw.text((7, 0), rand_str, fill=(0, 0, 0), font=font) # position, content, color, fontdel drawrequest.session['captcha'] = rand_str.lower() # store the content in Django's session storebuf = cStringIO.StringIO() # a memory buffer used to store the generated imageimage.save(buf, 'jpeg')return HttpResponse(buf.getvalue(), 'image/jpeg') # return the image data stream as image/jpeg format, browser will treat it as an image接下来,在项目的urls.py中,做好url映射即可:

urlpatterns += patterns('accounts.views',url(r'^accounts/captcha/$', 'captcha'),…)

在模板中的使用,也非常直观:

<div class="form-group"><img onclick="this.setAttribute('src','/accounts/captcha/?nocache='+Math.random());" src="/accounts/captcha/" alt="Captcha"/></div>这样就能在页面上显示出相应的验证码图片。这样,通过用户在提交表单之前,输入的图片中的内容,在请求到达服务器之后,,与其当前session中的内容比对,就可以判断用户是否输入了正确的验证码,继而进行相应的处理。

以上验证码图片的生成需要用到第三方的Pillow模块,可以通过 pip install Pillow来安装,在这个过程中可能需要安装一些系统共享库来支持某些类型的图片格式,如果编译出现问题,在编译过程中都会有体现。

没有什么可留恋,只有抑制不住的梦想,

利用Pillow,几行代码实现的最简单的Django页面验证码功能

相关文章:

你感兴趣的文章:

标签云: