Python Pickled Passwords
这是我使用pickle的python密码系统。我知道这很糟糕,但这是我第一次吃泡菜。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import pickle import os userlist = {'user1':'userpass1', 'user2':'userpass2'} users = open ("users.pkl", 'wb') pickle.dump (userlist, users) username = input ("Enter your username:") password = input ("Enter your password:") if (username in userlist) and (password == userlist[username]): print ("Access Granted") else: newaccount = input ("User not found. Shall I create a new account?") if newaccount =="yes": username = input ("Please enter your username:") password = input ("Please enter yout password:") userlist.update({username:password}) pickle.dump (userlist, users) users.close() |
我的问题是,每当我要添加一个新帐户时,使用此部分:
1 2 3 4 5 6 7 | newaccount = input ("User not found. Shall I create a new account?") if newaccount =="yes": username = input ("Please enter your username:") password = input ("Please enter yout password:") userlist.update({username:password}) pickle.dump (userlist, users) users.close() |
它似乎添加了它(看起来像是在使用记事本的pickle文件中),但是,我重新启动了python文件,它没有看到它。
我认为这与这部分有关:
1 2 3 4 5 | userlist = {'user1':'userpass1', 'user2':'userpass2'} users = open ("users.pkl", 'wb') pickle.dump (userlist, users) |
感谢您的帮助!D
每次使用
1 | users = open ("users.pkl", 'wb') |
如果您想要获取以前的pickled项,那么您需要查看文件是否已经存在,以及
如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from tempfile import NamedTemporaryFile try: # see if we have run this before with open ("users.pkl", 'rb') as users: users_dict = pickle.load(users) except IOError: # if not set to defualt users_dict = {'user1':'userpass1', 'user2':'userpass2'} username = input ("Enter your username:") password = input ("Enter your password:") if users_dict.get(username) == password: # unless a password can be None we can use get print ("Access Granted") else: newaccount = input("User not found. Shall I create a new account?") if newaccount =="yes": username = input("Please enter your username:") password = input ("Please enter yout password:") users_dict[username] = password # just use key = value with NamedTemporaryFile("wb",dir=os.path.dirname("users.pkl"),delete=False) as f: # in case we get exception use temp file pickle.dump (users_dict, f) os.replace(f.name,"users.pkl") # update original |