Skip to content
Advertisement

Load and Save Dictionary and Class Instances Python Script

Writing a python script that prompts the user by asking if they are are new or an existing user. If new, they will create a username, password, age. A User class instance should be created with that information along with adding the new username and password to the security dictionary. Once registered, or an existing user, it will be prompted to enter the username and password.

The username and password will be checked in the security dictionary (key is username, value is password). If in the dictionary, then the user can run a couple commands that affect the user class instance. For example, a function to increase the age by 1 (for birthdays).

Question: How do I load and save the security dictionary (username and password) and the user class instances (database for the user data: username, password, age, and height) so that a user can login in and out?

Here is my code:

class users:
    def __init__(self, username, password, age):
        self.username = username
        self.password = password
        self.age = age

    @classmethod
    def register(cls):
        return cls(
            str(input("Email: ")),
            int(input("ID Pin Number XXXX: ")),
            int(input("Age: "))
       )

    def load_func(file):
        #Open the security file if present
        if file == "security":
            try:
                with open("security.txt", "rb") as sct:
                    return pickle.load(sct)
            except IOError:
                with open("security.txt", "w+") as sct:
                    pickle.dump(dict(), sct)
                    return dict()
        elif file == "userDatabase":
            try:
                with open("userDatabase.txt", "rb") as dat:
                    return pickle.load(dat)
            except IOError:
                with open("userDatabase.txt", "w+") as dat:
                    pickle.dump(dict(), dat)
                    return dict()

    def saveData(file, data):
        if file == "security":
            with open("security.txt", "wb") as sct:
                pickle.dump(data, sct)
        elif file == "userDatabase":
            with open("userDatabase.txt", "wb") as dat:
                pickle.dump(data, dat)
        else:
            print("Error with saving file")

Advertisement

Answer

First of all: If you ever save passwords from users other than fictive testing users, be sure to hash the passwords using hashlib.

Now to your problem: Your users class is meant to represent one single user and should be renamed to User, in order to match PEP8 code standard (classes are CapitalLetters) and because it’s more intuitive that a class named User represents one user.

You could then save the username and password combination using dill. Later on, you could load the dill string to re-create the exact object that it was before saving:

import dill


class User:
    def __init__(self, username, password, age):
        self.username = username
        self.password = password
        self.age = age

    @classmethod
    def register(cls):
        return cls(
            str(input("Email: ")),
            int(input("ID Pin Number XXXX: ")),
            int(input("Age: "))
        )

    @classmethod
    def load(cls, file: str):
        with open(file, "rb") as f:
            return dill.load(f)

    def save(self):
        with open(self.username, "wb") as f:
            dill.dump(self, f)


Max = User("Max", "SecUrEP4$$W0rD", 42)
Max.save()

Max2 = User.load("Max")
print(Max2.username)

If you found this helpful, please leave an UP, if you have any further questions, leave a comment! :)

Advertisement