Python生成随机验证码的两种方法


Posted in Python onDecember 22, 2015

使用python生成随机验证码的方法有很多种,今天小编给大家分享两种方法,大家可以灵活运用这两种方法,设计出适合自己的验证码方法。

方法一:

利用range方法,对于range方法不清楚的同学,请参考文章《python开发的range()函数》

# -*- coding: utf-8 -*-
import random
def generate_verification_code(len=6):
 ''' 随机生成6位的验证码 '''
 # 注意: 这里我们生成的是0-9A-Za-z的列表,当然你也可以指定这个list,这里很灵活
 # 比如: code_list = ['P','y','t','h','o','n','T','a','b'] # PythonTab的字母
 code_list = [] 
 for i in range(10): # 0-9数字
  code_list.append(str(i))
 for i in range(65, 91): # 对应从“A”到“Z”的ASCII码
  code_list.append(chr(i))
 for i in range(97, 123): #对应从“a”到“z”的ASCII码
  code_list.append(chr(i))
 myslice = random.sample(code_list, len) # 从list中随机获取6个元素,作为一个片断返回
 verification_code = ''.join(myslice) # list to string
 return verification_code

方法二:

利用randint方法

# -*- coding: utf-8 -*-
import random
def generate_verification_code_v2():
 ''' 随机生成6位的验证码 '''
 code_list = []
 for i in range(2):
  random_num = random.randint(0, 9) # 随机生成0-9的数字
  # 利用random.randint()函数生成一个随机整数a,使得65<=a<=90
  # 对应从“A”到“Z”的ASCII码
  a = random.randint(65, 90)
  b = random.randint(97, 122)
  random_uppercase_letter = chr(a)
  random_lowercase_letter = chr(b)
  code_list.append(str(random_num))
  code_list.append(random_uppercase_letter)
  code_list.append(random_lowercase_letter)
 verification_code = ''.join(code_list)
 return verification_code

测试:

code = generate_verification_code(6)
code2 = generate_verification_code_v2()
print code
print code2

输出结果:

Glc5Tr
Hr6t7B

我个人更倾向于第一种方法,更加灵活,可以随意设置验证码长度。

Python 随机生成中文验证码

# -*- coding: utf-8 -*- 
import Image,ImageDraw,ImageFont 
import random 
import math, string 
class RandomChar(): 
 """用于随机生成汉字""" 
 @staticmethod 
 def Unicode(): 
 val = random.randint(0x4E00, 0x9FBF) 
 return unichr(val) 
 @staticmethod 
 def GB2312(): 
 head = random.randint(0xB0, 0xCF) 
 body = random.randint(0xA, 0xF) 
 tail = random.randint(0, 0xF) 
 val = ( head << 8 ) | (body << 4) | tail 
 str = "%x" % val 
 return str.decode('hex').decode('gb2312') 
class ImageChar(): 
 def __init__(self, fontColor = (0, 0, 0), 
      size = (100, 40), 
      fontPath = 'wqy.ttc', 
      bgColor = (255, 255, 255), 
      fontSize = 20): 
 self.size = size 
 self.fontPath = fontPath 
 self.bgColor = bgColor 
 self.fontSize = fontSize 
 self.fontColor = fontColor 
 self.font = ImageFont.truetype(self.fontPath, self.fontSize) 
 self.image = Image.new('RGB', size, bgColor) 
 def rotate(self): 
 self.image.rotate(random.randint(0, 30), expand=0) 
 def drawText(self, pos, txt, fill): 
 draw = ImageDraw.Draw(self.image) 
 draw.text(pos, txt, font=self.font, fill=fill) 
 del draw 
 def randRGB(self): 
 return (random.randint(0, 255), 
   random.randint(0, 255), 
   random.randint(0, 255)) 
 def randPoint(self): 
 (width, height) = self.size 
 return (random.randint(0, width), random.randint(0, height)) 
 def randLine(self, num): 
 draw = ImageDraw.Draw(self.image) 
 for i in range(0, num): 
  draw.line([self.randPoint(), self.randPoint()], self.randRGB()) 
 del draw 
 def randChinese(self, num): 
 gap = 5 
 start = 0 
 for i in range(0, num): 
  char = RandomChar().GB2312() 
  x = start + self.fontSize * i + random.randint(0, gap) + gap * i 
  self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB()) 
  self.rotate() 
 self.randLine(18) 
 def save(self, path): 
 self.image.save(path)
Python 相关文章推荐
在Python中实现贪婪排名算法的教程
Apr 17 Python
Python的Django框架中settings文件的部署建议
May 30 Python
利用Python如何制作好玩的GIF动图详解
Jul 11 Python
Python使用matplotlib绘制三维图形示例
Aug 25 Python
Python eval的常见错误封装及利用原理详解
Mar 26 Python
python2.7使用plotly绘制本地散点图和折线图
Apr 02 Python
pyQt5实时刷新界面的示例
Jun 25 Python
python读取dicom图像示例(SimpleITK和dicom包实现)
Jan 16 Python
浅谈pandas.cut与pandas.qcut的使用方法及区别
Mar 03 Python
python3 正则表达式基础廖雪峰
Mar 25 Python
通俗易懂了解Python装饰器原理
Sep 17 Python
Jupyter Notebook安装及使用方法解析
Nov 12 Python
基于python实现微信模板消息
Dec 21 #Python
python如何实现远程控制电脑(结合微信)
Dec 21 #Python
python从入门到精通(DAY 3)
Dec 20 #Python
python从入门到精通(DAY 2)
Dec 20 #Python
利用python代码写的12306订票代码
Dec 20 #Python
python从入门到精通(DAY 1)
Dec 20 #Python
在DigitalOcean的服务器上部署flaskblog应用
Dec 19 #Python
You might like
php foreach 参数强制类型转换的问题
2010/12/10 PHP
php 短链接算法收集与分析
2011/12/30 PHP
php使用正则表达式获取图片url的方法
2015/01/16 PHP
php函数连续调用实例分析
2015/07/30 PHP
PHP连接MySQL数据库并以json格式输出
2018/05/21 PHP
Enter回车切换输入焦点实现思路与代码兼容各大浏览器
2014/09/01 Javascript
解决Vue2.x父组件与子组件之间的双向绑定问题
2018/03/06 Javascript
javascript+HTML5 canvas绘制时钟功能示例
2019/05/15 Javascript
详解element-ui设置下拉选择切换必填和非必填
2019/06/17 Javascript
js回调函数原理与用法案例分析
2020/03/04 Javascript
Jquery使用each函数实现遍历及数组处理
2020/07/14 jQuery
python生成随机验证码(中文验证码)示例
2014/04/03 Python
Python中的startswith和endswith函数使用实例
2014/08/25 Python
30分钟搭建Python的Flask框架并在上面编写第一个应用
2015/03/30 Python
Python使用requests发送POST请求实例代码
2018/01/25 Python
python占位符输入方式实例
2019/05/27 Python
python3使用腾讯企业邮箱发送邮件的实例
2019/06/28 Python
python格式化输出保留2位小数的实现方法
2019/07/02 Python
简单了解python反射机制的一些知识
2019/07/13 Python
Python+Tensorflow+CNN实现车牌识别的示例代码
2019/10/11 Python
matlab、python中矩阵的互相导入导出方式
2020/06/01 Python
Python爬虫之Spider类用法简单介绍
2020/08/04 Python
详解anaconda安装步骤
2020/11/23 Python
英国家用电器折扣网站:Electrical Discount UK
2018/09/17 全球购物
既然说Ruby中一切都是对象,那么Ruby中类也是对象吗
2013/01/26 面试题
个人简历的自荐信
2013/10/23 职场文书
入党积极分子学习两会心得体会范文
2014/03/17 职场文书
二手房买卖协议书
2014/04/10 职场文书
应届毕业生自荐书
2014/06/18 职场文书
2014国庆节商场促销活动策划方案
2014/09/16 职场文书
社保代办委托书怎么写
2014/10/06 职场文书
学习党章的体会
2014/11/07 职场文书
优秀共产党员事迹材料
2014/12/18 职场文书
肖申克的救赎观后感
2015/06/02 职场文书
七年级思品教学反思
2016/02/20 职场文书
为什么mysql字段要使用NOT NULL
2021/05/13 MySQL