如何从pickle转储,加载和读取信息

时间:2014-07-14 21:21:09

标签: python pickle

我正在创建一些代码,询问用户一些问题并将其数据存储在列表中。我希望能够保存该列表并存储它,以便当它们返回时,它们可以在它们停止的地方继续拾取。这是一个简单的程序,所以我不想让它变得非常复杂。我可以用泡菜来完成这个吗?

import pickle

username = raw_input("Choose a username \n")
password = raw_input("Choose a password \n")
username_password = {}

def save_progress(save):

if 'yes' in save:
    username_password[username] = password

    with open('filename.pickle', 'wb') as handle:
            pickle.dump(like_people, handle) #like_people is a list with data
            pickle.dump(username_password, handle)
    return "Progress saved"

elif 'no' in save:
    print "Alright we won't save your progress"

else:
    print "I don't know what happened"

print save_progress(raw_input("Would you like to save your progress \n").lower())

如果我想创建一个功能

def load_progress(load):
    if 'yes' in load:
        #have them input their username
        #have them input their password
        #How would I check to see if that username + password matched what they originally
        #inputted and if so, load their progress
    elif 'no' in load:
        return "Alright we won't be loading"
    else:
        print "I don't know what is happening"

我甚至可以使用泡菜来完成这个任务吗?如果我需要编辑或添加任何内容,请告诉我,我会。

1 个答案:

答案 0 :(得分:2)

就泡菜而言,答案是:

with open('filename.pickle', 'rb') as infile:
    loaded_people = pickle.load(infile)
    loaded_user = pickle.load(infile)
#have them input their username
#have them input their password
if username_password.get(username) == password:
    print 'OK, loaded'
    like_people = loaded_data
    username_password = loaded_user
else:
    raise Exception('nice try but no cigar')

但是,从安全的角度来看,保存密码就像开头一样可疑。

如果用户可以阅读该文件,他们可以查看自己的用户名和密码,并在运行程序时输入。由于用户(尽管被告知不要)通常使用相同的密码来处理不同的事情,即使您实际上并不关心事物的安全性,它也会冒着泄露密码的风险。你是保护。

修复此问题与pickle文件,查找密码哈希和/或使用HMAC签名无关。如果您还想让数据本身对可以读取文件但又不知道密码的人保密,则需要加密。

或者,如果您根本不需要任何安全性,只需要一个与此存储数据关联的名称,然后删除"密码"完全。如果真的不是这样的话,那就没有必要让它看起来像登录。