django 验证码生成

先安装 PIL   参考我的另外一篇文章  http://hi.baidu.com/quqiufeng/blog/item/185fd719ad0f2261dab4bd25.html

安装 pycaptcha    svn checkout  http://svn.navi.cx/misc/trunk/pycaptcha/    后  python setup.py install  安装

下载 django-pycaptcha  地址  https://code.google.com/p/django-pycaptcha/   

svn checkout http://django-pycaptcha.googlecode.com/svn/trunk

 

在模板中使用  <img  src="/code/"> 做验证码图片

urls.py 中设置  

from views import show

urlpatterns  加一条  (r'^code/',show),

 

生成验证码的视图函数在  views.py

 

def showcode(request):
  from Captcha.Visual.Tests import PseudoGimpy
  g = PseudoGimpy()
  i = g.render()
  out = StringIO()
  i.save(out, "GIF")
  out.seek(0)
  response = HttpResponse()
  response['Content-Type'] = 'image/gif'
  response.write(out.read())
  return response

 

中文验证码

先要传一个中文字体到  C:\Python27\Lib\site-packages\Captcha\data\fonts\cn 文件夹

我使用的是  msyh.ttf  msyhbd.ttf yahei_mono.ttf

生成验证码的代码如下

from cStringIO import StringIO
import random

from Captcha.Visual import Text, Backgrounds, Distortions,ImageCaptcha
from Captcha.Words import WordList

 

class SmallerCaptcha(ImageCaptcha):
    defaultSize = (130,30)

    def getLayers(self):
        #word = WordList('basic-english').pick()
        word  = u'哇咔咔'
        self.addSolution(word)
        return [random.choice([Backgrounds.CroppedImage(), Backgrounds.TiledImage()]),
                Text.TextLayer(word, borderSize=1, fontFactory=Text.FontFactory(18, "cn/msyhbd.ttf")),
                Distortions.SineWarp()]

 

def show(request):
  g = SmallerCaptcha()
  i = g.render()
  out = StringIO()
  i.save(out, "GIF")
  out.seek(0)
  response = HttpResponse()
  response['Content-Type'] = 'image/gif'
  response.write(out.read())
  return response

posted @ 2011-10-27 11:37  秋丰  阅读(1033)  评论(0)    收藏  举报