`
yzjklove
  • 浏览: 63754 次
  • 性别: Icon_minigender_1
  • 来自: 广东省惠州市
社区版块
存档分类
最新评论

在Django中实现验证码

阅读更多
在项目中用到验证码,懒得去找,自己随便写了一个:
views.py:
def get_check_code_image(request,image='media/images/checkcode.gif'):    
    import Image, ImageDraw, ImageFont, random    
    im = Image.open(image)    
    draw = ImageDraw.Draw(im)    
    mp = md5.new()    
    mp_src = mp.update(str(datetime.now()))    
    mp_src = mp.hexdigest()    
    rand_str = mp_src[0:4]       
    draw.text((10,10), rand_str[0], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))    
    draw.text((48,10), rand_str[1], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))    
    draw.text((85,10), rand_str[2], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))    
    draw.text((120,10), rand_str[3], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50)))    
    del draw    
    request.session['checkcode'] = rand_str    
    buf = cStringIO.StringIO()    
    im.save(buf, 'gif')    
    return HttpResponse(buf.getvalue(),'image/gif') 


urls.py:
from django.conf.urls.defaults import *    
   
urlpatterns = patterns('tracer_server.apps.user.views',    
    # Uncomment this for admin:    
    # (r'^admin/', include('django.contrib.admin.urls')),    
        
    (r'^get_check_code_image/$', 'get_check_code_image'),    
   
)  


template:

<img onclick="this.setAttribute('src','/user/get_check_code_image/?nocache='+Math.random());" src="/user/get_check_code_image/" alt="CheckCode"/> 
分享到:
评论
1 楼 wl6179 2012-04-11  
貌似不错哦,如能上传一张效果图就完美了~

相关推荐

Global site tag (gtag.js) - Google Analytics