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读取word 中指定位置的表格及表格数据

python读取word 中指定位置的表格及表格数据

1.Word文档如下: 2.代码 # -*- coding: UTF-8 -*- from docx import Document def readSpecTable(filen...

python3实现SMTP发送邮件详细教程

python3实现SMTP发送邮件详细教程

简介   Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后...

Python字典推导式将cookie字符串转化为字典解析

cookie: PHPSESSID=et4a33og7nbftv60j3v9m86cro; Hm_lvt_51e3cc975b346e7705d8c255164036b3=156155...

使用python将时间转换为指定的格式方法

时间处理是在进行数据挖掘时很重要的一个方面,在参加比赛的时候很多比赛训练集给的时间和你最终要提交的时间格式是不同的。 我把我遇到的一种情况总结如下: 首先,题目给的格式是2016-09-...

使用matplotlib中scatter方法画散点图

使用matplotlib中scatter方法画散点图

本文实例为大家分享了用matplotlib中scatter方法画散点图的具体代码,供大家参考,具体内容如下 1、最简单的绘制方式 绘制散点图是数据分析过程中的常见需求。python中最有...