Python腌制密码

时间:2015-02-24 10:55:15

标签: python dictionary pickle

这是我使用pickle的python密码系统。这很糟糕,我知道,但这是我第一次吃泡菜。

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()

我的问题在于,每当我使用此部分添加新帐户时:

 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文件,它没有看到它。

我认为这与这部分有关:

userlist = {'user1':'userpass1', 'user2':'userpass2'}

users = open ("users.pkl", 'wb')

pickle.dump (userlist, users)

任何帮助表示赞赏! :d

1 个答案:

答案 0 :(得分:2)

每次使用w运行程序时都会覆盖:

users = open ("users.pkl", 'wb')

如果您想获取以前的腌制商品,则需要查看该文件是否已存在,并pickle.load获取之前的腌制商品,然后在代码末尾dump

如下所示:

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