import random def Verification_code(n): res=[[chr(i) for i in range(ord('0'),ord('9')+1)], [chr(i) for i in range(ord('a'),ord('z'))], [chr(i) for i in range(ord('A'),ord('Z'))]] yanzhengma='' for i in range(n): choice1=random.choice(res) choice2=random.choice(choice1) yanzhengma+=choice2 print(yanzhengma) return yanzhengma res=Verification_code(4) #檢驗驗證碼是否正確 def Verification_input(n): while True: re = Verification_code(n) code = input('請輸入括號里的驗證碼,不區分大小寫【{0}】:'.format(re)) if code.strip().lower() != re.lower(): print('您輸入的驗證碼有誤,請注意區分數字0和字母o 數字1和字母l') else: return True
Django 圖片驗證碼配置文件
創建utils目錄,接着創建random_check_code.py,在里邊寫函數rd_check_code
import random from PIL import Image,ImageFont,ImageDraw,ImageFilter def rd_check_code(width=100, height=35, char_length=4, font_file='kumo.ttf', font_size=35): # width:圖片寬度 height:圖片高度 char_length:驗證碼個數 font_file:驗證碼字體文件路徑 font_size:驗證碼字符大小 code = [] img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') def rndChar(): """ 生成隨機字母 :return: """ res = [[chr(i) for i in range(ord('0'), ord('9') + 1)], # 生成0到9 [chr(i) for i in range(ord('a'), ord('z'))], # 生成a到z [chr(i) for i in range(ord('A'), ord('Z'))]] # 生成A到Z choice1=random.choice(res) choice2=random.choice(choice1) return choice2 def rndColor(): """ 生成隨機顏色 :return: """ return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 寫文字 font = ImageFont.truetype(font_file, font_size) for i in range(char_length): char = rndChar() code.append(char) h = random.randint(0, 4) draw.text([i * width / char_length, h], char, font=font, fill=rndColor()) # 寫干擾點 for i in range(10): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) # 寫干擾圓圈 for i in range(10): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor()) # 畫干擾線 for i in range(3): x1 = random.randint(0, width) y1 = random.randint(0, height) x2 = random.randint(0, width) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=rndColor()) img = img.filter(ImageFilter.DETAIL) # 濾鏡 return img, ''.join(code)
在視圖函數中調用
from django.shortcuts import render,redirect,HttpResponse def check_code(request): from io import BytesIO from utils.random_check_code import rd_check_code img,code = rd_check_code() stream = BytesIO() img.save(stream, 'png') data = stream.getvalue() request.session['code'] = code return HttpResponse(data)
