从值python 3中的类的属性获取字典键

时间:2015-10-01 19:59:31

标签: python python-3.x authentication dictionary

我的服务器有一个用户类:

class User():
    def __init__(self, username, password, group, join_date):
        self.password = password
        self.group = group
        self.join_date = join_date

我还有一个字典,其中包含用户ID作为键。添加用户的格式为:

users = {
    1443: User("Bob", "my_password", "admin", "June 23")
}

我的问题是当用户登录他们的帐户时:

username = input()
password = getpass.getpass()

我希望有类似的东西:

if username in users:
    if users[username].password == password

我不能这样做,因为我不知道如何从用户的用户名中获取用户ID,因为它嵌入在对象中。任何想法或建议?我是认证/授权的新手。

1 个答案:

答案 0 :(得分:1)

你有两种选择;循环遍历所有对象并找到与登录名匹配的用户,或者从用户名映射到用户ID或直接映射到用户对象。

循环需要对users字典的所有值进行线性搜索:

for user in users:
    if user.username == username and user.password == password:
        # success!

您可以生成一次从用户名到用户ID的映射,然后使用该映射:

usernames = {user.username: userid for userid, user in users.items()}

然后使用:

if username in usernames:
    userid = usernames[username]
    if users[userid].password == password

这比每次线性搜索快得多,映射中的直接查找是O(1)恒定时间查找。

您可以直接将映射点指向用户对象:

usernames = {user.username: user for userid, user in users.items()}

如果您的程序添加或删除用户,您还需要维护此额外映射。