Python登录限制

  • 本文关键字:登录 Python python
  • 更新时间 :
  • 英文 :


我正试图在当前代码中实现登录尝试系统,但我不知道该在哪里打勾。有人能提出什么建议吗?我想尝试三次登录,如果用户登录失败,系统会将用户锁定。我只是不知道该把代码放在哪里。

granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")

解决此问题的更好方法是使用JSON文件而不是txt文件。您可以使用以下格式的文件:

{
"username": {
"password": "",
"attempts": 0,
}
}

login()函数中,如果密码错误,则递增并写入尝试次数。在函数开始读取JSON并检查attempts值是否大于3之前。如果更大,则发送适当的消息,否则继续登录操作并要求输入密码。

你的代码有一些小错误,我在这里处理过:

import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0:                    # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "n"+name[0]+","+password)      # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)