隨機驗證碼、圖片驗證碼和郵箱發送用戶驗證碼

隨機驗證碼、圖片驗證碼和郵箱發送用戶驗證碼

1、隨機驗證碼

隨機驗證碼的生成比較簡單通常在註冊用戶的時候與郵箱或者手機信息接口相結合實現發送驗證碼功能,隨機驗證碼只須要使用python內置的random隨機數函數,調用random模塊:import random,具體實現代碼塊前端

#隨機驗證碼
def authCode():
    code = ''
    for i in range(6):
        current = random.randrange(0,6)#randrange隨機生成0-6的數字,但不包括6
        if current != i:
            temp=chr(random.randint(65,90))#chr()加數字是ASCII碼錶中的大寫A-Z字符
        else:
            temp=random.randint(0,9)#randint隨機生成65-90的數字,包括0和9
        code += str(temp) #字符串拼接
    return code  #返回到隨機生成的6位的驗證碼

2、圖片驗證碼

圖片驗證碼的生成是關於第三方庫pillow的使用,使用pillow中的PIL中的一些方法生成驗證碼圖片。其實pillow是在PIL的基礎上進行修改加工的,由於PIL因爲「年久失修」僅僅支持python2.7版本,因此pillow所以誕生,在PIL上面建立的兼容版本的pillow模塊,示例代碼塊:python

#author:wylkjj
#date:2019/12/19
#-*- coding:utf-8 -*-
import random #導入隨機函數模塊
'''
隨機驗證碼圖片
Image內部可能會有報錯問題,主要是由於沒有安裝python2.7,不過能夠忽略掉
Image:圖片
ImageDraw:畫筆
ImageFont:字符處理
ImageFilter: 濾鏡,邊界增強(閾值更大)
'''
from PIL import Image, ImageDraw, ImageFont, ImageFilter
'''
map(遍歷序列):接收兩個參數,一個是函數,一個是 Iterable,
map 將傳入的函數依次做用到序列的每一個元素,並把結果做爲新的 Iterator 返回
'''
letter_cases = "qwertyupasdfghjkxcvb"  # 小寫字母,去除可能干擾的i,l,o,z
upper_cases = letter_cases.upper()  # 大寫字母
numbers = ''.join(map(str, range(3, 10)))  # 3-10數字
init_chars = ''.join((letter_cases, upper_cases, numbers))
def create_validate_code(size=(90, 30),
                         chars=init_chars,
                         img_type="GIF",
                         mode="RGB",
                         bg_color=(255, 255, 255),
                         fg_color=(0, 0, 255),
                         font_size=18,
                         font_type="simfang.ttf",
                         length=4,
                         draw_lines=True,
                         n_line=(1, 2),
                         draw_points=True,
                         point_chance = 2):
    '''
    @todo: 生成驗證碼圖片
    @param size: 圖片的大小,格式(寬,高),默認爲(90, 30)
    @param chars: 容許的字符集合,格式字符串
    @param img_type: 圖片保存的格式,默認爲GIF,可選的爲GIF,JPEG,TIFF,PNG
    @param mode: 圖片模式,默認爲RGB
    @param bg_color: 背景顏色,默認爲白色
    @param fg_color: 前景色,驗證碼字符顏色,默認爲藍色#0000FF
    @param font_size: 驗證碼字體大小
    @param font_type: 驗證碼字體,默認爲 ae_AlArabiya.ttf
    @param length: 驗證碼字符個數
    @param draw_lines: 是否劃干擾線
    @param n_lines: 干擾線的條數範圍,格式元組,默認爲(1, 2),只有draw_lines爲True時有效
    @param draw_points: 是否畫干擾點
    @param point_chance: 干擾點出現的機率,大小範圍[0, 100]
    @return: [0]: PIL Image實例
    @return: [1]: 驗證碼圖片中的字符串
    '''
    width, height = size # 寬, 高
    img = Image.new(mode, size, bg_color) # 建立圖形
    draw = ImageDraw.Draw(img) # 建立畫筆
    def get_chars():
        '''生成給定長度的字符串,返回列表格式(以length的數量返回chars)'''
        return random.sample(chars, length)
    def create_lines():
        '''繪製干擾線'''
        line_num = random.randint(*n_line) # 干擾線條數
        for i in range(line_num):
            #起始點
            begin = (random.randint(0, size[0]), random.randint(0, size[1]))
            #結束點
            end = (random.randint(0, size[0]), random.randint(0, size[1]))
            draw.line([begin, end], fill=(0, 0, 0))#fill背景色
    def create_points():
        '''繪製干擾點'''
        chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100],省去了if else的複雜操做
        for w in range(width):
            for h in range(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w, h), fill=(0, 0, 0))#背景色
    def create_strs():
        '''繪製驗證碼字符'''
        c_chars = get_chars()
        strs = ' %s ' % ' '.join(c_chars) # 每一個字符先後以空格隔開
        font = ImageFont.truetype(font_type, font_size)
        font_width, font_height = font.getsize(strs)
        draw.text(((width - font_width) / 3, (height - font_height) / 3),
                    strs, font=font, fill=fg_color)
        return ''.join(c_chars)
    if draw_lines:
        create_lines()
    if draw_points:
        create_points()
    strs = create_strs()
    # 圖形扭曲參數
    params = [1 - float(random.randint(1, 2)) / 100,
              0,0,0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
              ]
    img = img.transform(size, Image.PERSPECTIVE, params) # 建立扭曲
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 濾鏡,邊界增強(閾值更大)
    return img, strs
#生成驗證碼圖片(測試時能夠直接調用打印數據類型判斷是否生成數據)
img,strs=create_validate_code()
print(type(img),type(strs))
#生成驗證碼圖片
import io #要導入io模塊
def checkCode(req):
    stream = io.BytesIO()
    #建立隨機字符串 code
    #建立一張圖片格式的字符串,將隨機字符串寫到圖片上
    img,code = create_validate_code()
    img.save(stream,"PNG")
    #將字符串形式的驗證碼放在Session中
    req.session["checkCode"]=code
    return HttpResponse(stream.getvalue()) #把數據返回到前端

3、郵箱發送用戶驗證碼

郵箱發送用戶驗證碼一般結合上面的隨機驗證碼一塊兒使用:把從上面得到到的數據以郵箱的方式發送到用戶郵箱中。注:發送郵件的又想要打開SMTP服務,生成受權碼,用受權碼代替郵箱的密碼進行登陸操做,要使用與其郵箱相符的SMTP和端口號進行發送,下面例子使用的是網易163郵箱帳號,具體的開啓SMTP服務的操做請自行百度。session

#郵箱發送功能
def email(email_list, content, subject="抽屜新熱榜-用戶註冊"):
    msg = MIMEText(content, 'plain', 'utf-8')
    #發件人和發件郵箱
    msg['From'] = formataddr(["抽屜新熱榜",'######@163.com'])
    #郵件主題
    msg['Subject'] = subject
    # SMTP服務
    server = smtplib.SMTP("smtp.163.com", 25) #郵箱的smtp和端口
    # SMTP登陸網易郵箱帳號
    server.login("######@163.com", "######")
    # 發送的郵箱
    server.sendmail('######@163.com', email_list, msg.as_string())
    server.quit()
#調用此函數就能夠直接使用郵箱發送了
email(["要給發送的人的郵箱地址",], "要發送的內容")
相關文章
相關標籤/搜索