How to create a python dictionary that will store

2019-06-04 14:29发布

问题:

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):

def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
    userName = input("Please Set Your New Username: ")
    password = input("Please Set Your New Password: ")
//  if (userName in dictAcc):
        print("Username is taken")
        userPass()
    else:
//      dictAcc[userName] = password 
        print("Congratulations! You have succesfully created an account!")
        time.sleep(1.5)
        dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
    login()
else:
    print("Invalid answer, try again")
    userPass()


def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
//  for key in dictAcc:
//      if (loginUserName == key and loginPass == dictAcc[key]):
//          print("You have successfully logged in!")
            dataInput()
        else:
            print("Please try again")
            tries += 1
            login()
        if (tries >= 3):
            print("You have attempted to login too many times. Try again later.")
            time.sleep(300)
            login()

userPass()

回答1:

As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.

Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).

import pickle
import time

def loaddict():
    try:
        with open("dictAcc.txt", "rb") as pkf:
            return pickle.load(pkf)
    except IOError:
        with open("dictAcc.txt", "w+") as pkf:
            pickle.dump(dict(), pkf)
            return dict()

def savedict(dictAcc):
    with open("dictAcc.txt", "wb") as pkf:
        pickle.dump(dictAcc, pkf)


def userPass():
    dictAcc = loaddict() #Load the dict
    checkAccount = raw_input("Do you have an account (Y or N)?")
    if (checkAccount == 'N' or checkAccount == 'n'):
        userName = raw_input("Please Set Your New Username: ")
        password = raw_input("Please Set Your New Password: ")
        if (userName in dictAcc):
            print("Username is taken")
            userPass()
        else:
            dictAcc[userName] = password 
            print("Congratulations! You have succesfully created an account!")
            savedict(dictAcc) #Save the dict
            time.sleep(1.5)
            # dataInput() Code ends
    elif(checkAccount == 'Y' or checkAccount == 'y'):
        login()
    else:
        print("Invalid answer, try again")
        userPass()


def login():
    global userName
    global password
    global tries
    loginUserName = raw_input("Type in your Username: ")
    loginPass = raw_input("Type in your Password: ")
    dictAcc = loaddict() #Load the dict
    if (tries < 3):
        for key in dictAcc:
            if (loginUserName == key and loginPass == dictAcc[key]):
                print("You have successfully logged in!")
                # dataInput() Code ends
            else:
                print("Please try again")
                tries += 1
                login()
            if (tries >= 3):
                print("You have attempted to login too many times. Try again later.")
                time.sleep(3)
                tries=1 #To restart the tries counter
                login()

global tries
tries=1
userPass()


回答2:

There are different ways to do this. I'll mention two.

As you noticed, all variables created by your program are erased when the program finishes executing.

One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.

However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.

You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.



回答3:

How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.

Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.

So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.

A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.