django(一)验证码
这里讲讲在django中使用第三方插件验证码的流程。
一、 先安装pillow, 通过 python -m pip install pillow
二、安装完后,在官方网站上看操作过程。地址:pillow.readthedocs.io/en/
三、视图部分逻辑代码--
1、验证码部分 ( 注意:验证码要用全局变量来使得后期可以和输入的值进行验证)
def verifycode(request): from PIL import Image, ImageDraw, ImageFont import random #background bgColor = (random.randrange(50,100),random.randrange(50,100),random.randrange(50,100)) #hight and length width = 100 height = 25 #create a canvas image = Image.new('RGB',(width,height),bgColor) # #font = ImageFont.truetype('FreeMono.ttf',24) #create a pen draw = ImageDraw.Draw(image) #create a global empty string for verify code global textTemp textTemp='' #create char for i in range(4): textTemp1 = text[random.randrange(0, len(text))] textTemp += textTemp1 draw.text((i*25,0) , #text[random.randrange(0,len(text))] textTemp1 , (255,255,255), ) request.session['code']=textTemp #draw.text((0,0),text,(255,255,255)) #save from io import BytesIO as StringIO buf = StringIO() image.save(buf,'png') #output to clinet return HttpResponse(buf.getvalue(),'image/png')
2、表格页面一的视图逻辑
def verifyTest1(request): return render(request, 'booktest/verifyTest1.html')
3、验证输入的视图逻辑
def verifyTest2(request): code = request.POST['code'] if( code == textTemp ): return HttpResponse('You got it') return HttpResponse('False')
四、创建模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <image src="/booktest/verifycode"></image><br> <form action="verifyTest1" method="post"> {% csrf_token %} <input type="text" name ="code1"> <input type="submit" name="submit"> </form> </body> </html>
#创建模板如果把 “form” 写成 “from” 就没法跳转了
五、创建url
url(r'^verifycode/$', views.verifycode), url(r'^verifyTest1/$', views.verifyTest1), url(r'^verifyTest2/$', views.verifyTest2)
六、效果
当输入的验证码错误,会返回“false”。 正确则返回“You got it.”