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

yipeiwu_com5年前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生成词云的实现代码

Python生成词云的实现代码

1 概述 利用Python生成简单的词云,需要的工具是cython,wordcloud与anaconda. 2 准备工作 包括安装cython,wordcloud与anaconda. 2...

pandas 使用均值填充缺失值列的小技巧分享

pd.DataFrame中通常含有许多特征,有时候需要对每个含有缺失值的列,都用均值进行填充,代码实现可以这样: for column in list(df.columns[df.i...

Python标准库之随机数 (math包、random包)介绍

我们已经在Python运算中看到Python最基本的数学运算功能。此外,math包补充了更多的函数。当然,如果想要更加高级的数学功能,可以考虑选择标准库之外的numpy和scipy项目,...

安装2019Pycharm最新版本的教程详解

安装2019Pycharm最新版本的教程详解

1下载安装 1.1打开官网 http://www.jetbrains.com/pycharm/download/ 耐心等待,大概200M,几分钟左右 1.2.双击下载好的exe,得到...

Python遍历文件夹 处理json文件的方法

有两种做法:os.walk()、pathlib库,个人感觉pathlib库的path.glob用来匹配文件比较简单。 下面是第二种做法的实例(第一种做法百度有很多文章): from...