python实现简单登陆流程的方法

yipeiwu_com6年前Python基础

登陆流程图:

代码实现:

#-*- coding=utf-8 -*-
import os,sys,getpass
'''
user.txt 格式
账号 密码 是否锁定 错误次数
jack 123 unlock 0
tom 123 unlock 0
lily 123 unlock 0
hanmeimei 123 unlock 0
lucy 123 unlock 0
'''
# 定义写入文件的函数
def wirte_to_user_file(users,user_file_path):
	user_file = file(user_file_path,'w+')
	for k,v in users.items():
		line = []
		line.append(k)
		line.extend(v)
		user_file.write(' '.join(line)+'\n')
	user_file.close()
# 判断用户文件是否存在,不存在直接退出
user_file_path = 'users.txt'
if os.path.exists(user_file_path):
	user_file = file(user_file_path,'r')
else:
	print 'user file is not exists'
	sys.exit(1)
# 遍历用户文件,将用户包装成字典
users_dic = {}
for user_line in user_file:
	user = user_line.strip().split()
	users_dic[user[0]] = user[1:]
'''
{
	'lucy': ['123', 'unlock', '0'], 
	'lily': ['123', 'unlock', '0'], 
	'jack': ['123', 'unlock', '0'], 
	'hanmeimei': ['123', 'unlock', '0'], 
	'tom': ['123', 'unlock', '0']
}
'''
while True:
	# 输入账号
	input_name = raw_input('please input your username,input "quit" or "q" will be exit : ').strip()
	# 判断是否为退出
	if input_name == 'quit' or input_name == 'q':
		sys.exit(0)
	# 输入密码
	password = getpass.getpass('please input your password:').strip()
	# 判断账号是否存在、是否锁定
	if input_name not in users_dic:
		print 'username or password is not right'
		break
		
	if users_dic[input_name][1] == 'lock':
		print 'user has been locked'
		break
	
	# 判断密码是否正确,正确,登陆成功
	if str(password) == users_dic[input_name][0]:
		print 'login success,welcome to study system'
		sys.exit(0)
	else:
		# 如果密码错误则修改密码错误次数
		users_dic[input_name][2] = str(int(users_dic[input_name][2])+1)
		# 密码错误次数大于3的时候则锁定,并修改状态
		
		if int(users_dic[input_name][2]) >= 3:
			print 'password input wrong has 3 times,user will be locked,please connect administrator'
			users_dic[input_name][1] = 'lock'
			wirte_to_user_file(users_dic,user_file_path)
			break
		
		wirte_to_user_file(users_dic,user_file_path)

以上这篇python实现简单登陆流程的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中使用md5sum检查目录中相同文件代码分享

复制代码 代码如下: """This module contains code from Think Python by Allen B. Downey http://thinkpyth...

Python处理文本文件中控制字符的方法

控制字符 控制字符(Control Character),或者说非打印字符,出现于特定的信息文本中,表示某一控制功能的字符,如控制符:LF(换行)、CR(回车)、FF(换页)、DEL(...

Python实现拷贝多个文件到同一目录的方法

本文实例讲述了Python实现拷贝多个文件到同一目录的方法。分享给大家供大家参考,具体如下: 有一个文件,里面存有多个文件名,一个文件名一行。如果想把这些文件拷贝到一个目录,可以用下面的...

Python 查找字符在字符串中的位置实例

如下所示: str_1='wo shi yi zhi da da niu ' char_1='i' nPos=str_1.index(char_1) print(nPos) 运行结...

Python实现的线性回归算法示例【附csv文件下载】

Python实现的线性回归算法示例【附csv文件下载】

本文实例讲述了Python实现的线性回归算法。分享给大家供大家参考,具体如下: 用python实现线性回归 Using Python to Implement Line Regressi...