Django에서 인증 코드 구현

1848 단어 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"/> 

좋은 웹페이지 즐겨찾기