两个例子
我给你两个例子来说明如何做到这一点(毕竟是元旦):)
程序守则
您的代码有效,但您可能想尝试一下,更简洁一点:
users = {"User 1" : { 'pwd' : 'bandit', 'role': 'admin'},
"User 2" : { 'pwd' : 'orion', 'role': 'user'},
"User 3" : { 'pwd' : 'solar', 'role': 'approver'},
"User 4" : { 'pwd' : 'mars', 'role': 'editor'}
}
print "Enter your name."
answer = raw_input()
INTRUSION = True
if answer in users:
print "Hello %s. Please enter your passcode." % answer
password = raw_input()
if password == users[answer]['pwd']:
INTRUSION = False
if INTRUSION:
print "LOGIN DENIED. Your intrusion has been reported to the authorities."
else:
print "Login request accepted. Welcome to The Database."
print "Your role is %s." % users[answer]['role']
# ...you can now go on to do other stuff
它允许您参考用户字典并为他们分配不同的角色。您可能会发现在此版本上进行扩展更容易。
面向对象的例子
一个更扩展的示例使用更面向对象的方法:
from collections import namedtuple
import hashlib
# ---------------------------- SETUP
# data structure for holding user record in named fields
User = namedtuple('User', ['uid', 'pwd', 'role'])
# utility function to hash passwords and ensure they are
# stored in encrypted form
def hashed(s):
return hashlib.md5(s).hexdigest()
# Class to hold the user database
# Methods could be added here e.g. add and delete users
class UserBase(object):
def __init__(self, users={}):
self.database = {}
for user in users:
self.database[user.uid] = user
def get_user(self, uid):
return self.database.get(uid)
# These should be stored in a database with
# hashed passwords...
users = [User("User 1", hashed('bandit'), 'admin'),
User("User 2", hashed('orion'), 'user'),
User("User 3", hashed('solar'), 'approver'),
User("User 4", hashed('mars'), 'editor')]
# Instantiate the database
USERS = UserBase(users)
# ---------------------------- SETUP ENDED
# Simulate a login session
INTRUSION = True
uid = raw_input("Enter your name: ")
user = USERS.get_user(uid)
if user:
prompt = "Hello %s. Please enter your passcode: " % user.uid
password = raw_input(prompt)
if hashed(password) == user.pwd:
INTRUSION = False
if INTRUSION:
print "LOGIN DENIED. Your intrusion has been reported to the authorities."
else:
print "%s logged in. Welcome to The Database." % user.uid
print "Your role is %s." % user.role
# ...you can now go on to do other stuff
# there is an object called user that has
# three attributes: uid, pwd, and role