为什么这个泡菜实现不起作用(即我缺少了什么)

时间:2018-11-18 15:32:47

标签: python pickle

在此代码中,我尝试使用pickle永久存储用户创建新帐户但出现逻辑错误时创建的新用户名的值。并且字典中的值仍然保持不变。(我知道我显然在这里缺少明显的东西,但实际上我不知道那是什么)

# defining variables
create_username = 0
create_password = 0
password = 0
username = 0

# importing pickle
import pickle

# creates a users dictionary
users = {
    'Joe': 'juk725',
    'Mat': 'axr3',
    'Th3_j0k3r': 'bl4z3',
    'ag4r-j3lly': 'Micr0b3'
}

# sign up (creating new account)
while username not in users and username != 'signup':
    username = input("enter username(type signup to create an account): ")

    # add new user to dictionary
    if username == "signup" or username == "Signup":
        create_username = input("enter a new username: ")
        create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")

    if create_password in users:
        create_password = input("password taken re-enter: ")
    # then adds the new username to the users dictionary
    if username == 'signup':
        users[create_username] = create_password

    pickle.dump(users, open('pickle_file_name.p', 'wb'))



else:
    if username in users:
        password = input("enter password: ")

    if password in users:
        print("access granted")

    if username not in users:
        username = input("enter username: ")

    if password not in users:
        print("access denied")

1 个答案:

答案 0 :(得分:0)

您永远不会打开腌制的文件,因此您的代码会重复使用相同的字典输入。

您应该只创建一个脚本来首先创建pickle文件,然后用users方法调用替换您拥有的pickle.load的定义

# importing pickle
import pickle

# creates a users dictionary
with open('pickle_file_name.p', 'rb') as f:
    users = pickle.load(f)

# sign up 

如果您想要一个可读文件,我建议使用json模块而不是pickle。如果您想更轻松地查询用户,请sqlite3

在这里也不是很重要,但是对于任何带有帐户的项目,密码哈希都是一个好主意,而不是用明文存储数据