本文實例展示了Python生成驗證碼的方法,具有很好的實用價值。分享給大家供大家參考。具體實現方法如下:
前臺頁面代碼如下:
<div> <img id="authcode_img" alt="驗證碼" src="/registration/makeimage/{{time}}"/> <!-- time 任意隨機數(時間戳),防止頁面緩存 導致驗證碼不能更新--> <a href="javascript:refreshCode();" rel="external nofollow" style="color:blue;">看不清換一張</a></div><script> function refreshCode() { $('authcode_img').src = "/registration/makeimage/" + Math.random(); }</script>
后臺程序如下:
import StringIOimport Image, ImageDraw, ImageFont, random #相應的模塊需要安裝from xxx.settings import authcode_font #請確保改字體存在def make_image(request): mp = hashlib.md5() mp.update(str(datetime.datetime.now())+str(random.random())) mp_src = mp.hexdigest() rand_str = mp_src[0:6] font = ImageFont.truetype(authcode_font, 25) width = 75 height = 30 im = Image.new('RGB',(width,height),'#%s'%mp_src[-7:-1]) draw = ImageDraw.Draw(im) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.text((5,2), rand_str, font=font) del draw buffer = StringIO.StringIO() im.save(buffer,'jpeg') httpResponse = HttpResponse(content=buffer.getvalue(),mimetype="image/jpeg") request.session['auth_code'] = rand_str return httpResponse
程序效果如下:
新聞熱點
疑難解答