如何使用外部文本文件创建身份验证

时间:2019-04-26 13:13:26

标签: python authentication login text-files

作为大型程序的一部分,我需要根据外部txt文件检查某人的用户名和密码。

我是否需要在文本文件或其他内容中使用字典?

username = input("What is your username?")
password = input("Password?")

#To do: check username + password against external file users.txt
#users.txt is in the same directory as the program

2 个答案:

答案 0 :(得分:0)

好吧,如果您的密码未加密,则可以直接读取文件,并将其拆分为字典中具有不同用户名和密码的文件。

例如,如果文件的格式是用户和密码的每一行,并用空格分隔,则可以使用如下程序:

username = "username"
password = "password"

with open("users.txt", "r") as passwordsfile:
    passwordSeparator = " "
    # One line format, you can use one of the following solutions
    passwords = {
        x.split(passwordSeparator)[0]: x.split(passwordSeparator)[
            1
        ]  # x should be in "username password" format, so we have to split it
        for x in filter(
            None, passwordsfile.read().split("\n")
        )  # The filter function remove the empty lines
    }

    # Multiline solution:
    passwords = {}
    separatedLines = filter(None, passwordsfile.read().split("\n"))
    for x in separatedLines:
        _username = x.split(passwordSeparator)[0]
        _password = x.split(passwordSeparator)[1]
        passwords[_username] = _password


# print(passwords) : {"user1": "password1", "user2": "password2"}

# Check the user and password with assert
try:
    assert (
        passwords[username] == password
    )  # assert is useful to check a condition in our program. This is useful in a try/except bracket, because in this case, we have no guarentee that the username is in the password database
    print("You're logged in")
except:
    print("Wrong password or username!")

但是,如果您有大型用户数据库,则应该查看数据库存储(SQLite,MySQL等)的性能,并且可能必须加密用户密码。

答案 1 :(得分:0)

我从您的问题中得到的是您想要 创建一个登录/身份验证程序,以从文本文件中调用信息,

def main():    
username, password = get_name_and_password()  
registered_users = read_pwdfile('pwd_filename')  
if usr_pass_registered(username, password, registered_users):  
    registered = True  
else:  
    registered = get_registration(username, password, 'pwd_filename')  
if registered:  
    print(You are logged in)  

#您需要以csv格式(逗号分隔)保存用户名和密码