2つの例
これを行う方法について2つの例を示します(結局のところ、正月です):)
手続き型コード
あなたのコードは機能しますが、これを試してみることをお勧めします。
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