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解析xml模块封装代码
Feb 07 Python
python中bisect模块用法实例
Sep 25 Python
Python基于DES算法加密解密实例
Jun 03 Python
Python自定义线程池实现方法分析
Feb 07 Python
用tensorflow构建线性回归模型的示例代码
Mar 05 Python
解决python3中解压zip文件是文件名乱码的问题
Mar 22 Python
Pycharm2017版本设置启动时默认自动打开项目的方法
Oct 29 Python
Python笔记之观察者模式
Nov 20 Python
Python常用库大全及简要说明
Jan 17 Python
Python操作注册表详细步骤介绍
Feb 05 Python
使用ITK-SNAP进行抠图操作并保存mask的实例
Jul 01 Python
python实现过滤敏感词
May 08 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笔记之:日期函数的使用介绍
2013/04/24 PHP
ThinkPHP文件缓存类代码分享
2015/04/22 PHP
php ajax异步读取rss文档数据
2016/03/29 PHP
基于prototype的validation.js发布2.3.4新版本,让你彻底脱离表单验证的烦恼
2006/12/06 Javascript
关于JS控制代码暂停的实现方法分享
2012/10/11 Javascript
jQuery ui 利用 datepicker插件实现开始日期(minDate)和结束日期(maxDate)
2014/05/22 Javascript
javascript闭包的理解
2015/04/01 Javascript
实例讲解jQuery中对事件的命名空间的运用
2016/05/24 Javascript
微信小程序 教程之列表渲染
2016/10/18 Javascript
微信小程序实现多宫格抽奖活动
2020/04/15 Javascript
Vue多种方法实现表头和首列固定的示例代码
2018/02/02 Javascript
webstorm中配置nodejs环境及npm的实例
2018/05/15 NodeJs
webpack是如何实现模块化加载的方法
2019/11/06 Javascript
Vue 的 v-model用法实例
2020/11/23 Vue.js
[02:19]2014DOTA2国际邀请赛 专访820少年们一起去追梦吧
2014/07/14 DOTA
在Lighttpd服务器中运行Django应用的方法
2015/07/22 Python
python实现图书馆研习室自动预约功能
2018/04/27 Python
Python Django框架实现应用添加logging日志操作示例
2019/05/17 Python
详解解决Python memory error的问题(四种解决方案)
2019/08/08 Python
PIL包中Image模块的convert()函数的具体使用
2020/02/26 Python
python GUI库图形界面开发之pyinstaller打包python程序为exe安装文件
2020/02/26 Python
python torch.utils.data.DataLoader使用方法
2020/04/02 Python
浅谈Python __init__.py的作用
2020/10/28 Python
Django解决frame拒绝问题的方法
2020/12/18 Python
Photobook澳大利亚:制作相片书,婚礼卡,旅行相簿
2017/01/12 全球购物
Nuts.com:优质散装,批发坚果、干果和巧克力等
2017/03/21 全球购物
香港迪士尼乐园酒店预订:Hong Kong Disneyland Hotels
2017/05/02 全球购物
舒适的豪华鞋:Taryn Rose
2018/05/03 全球购物
高级销售员求职信
2013/10/25 职场文书
法学专业毕业生自荐信范文
2013/12/18 职场文书
充分就业社区汇报材料
2014/05/07 职场文书
质检员岗位职责
2015/02/03 职场文书
幼师中班个人总结
2015/02/12 职场文书
OpenCV-Python实现人脸磨皮算法
2021/06/07 Python
前端监听websocket消息并实时弹出(实例代码)
2021/11/27 Javascript
「女孩的钓鱼慢活」全新版权绘公布
2022/03/21 日漫