The example of this article shows the method of generating verification code in Python, which has good practical value. Share to everyone for your reference. The implementation methods are as follows:
The front page code is as follows:
<div>
<!--time Arbitrary random number (timestamp) to prevent page caching from causing the Authenticode to update-->
<a href= "Javascript:refreshcode ()" rel= "external" nofollow "color: Blue; " > I can't see another one </a>
</div>
<script>
function Refreshcode () {
$ (' authcode_img '). src = "/registration/makeimage/" + math.random ();
}
</script>
The background program is as follows:
Import Stringio Import 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,) width = height = im = I Mage.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
The effect of the program is as follows: