Python Unknown Error : Attribute Error with MongoDB database

Python Unknown Error : Attribute Error with MongoDB database

我写了一个程序,我试图将我的程序分散到多个 python 文件中。 但是它 returns 未知属性错误,我不知道如何解决。

我的代码有五个部分。 第一部分叫数据库,是我自己的数据库,里面有一些非真实的数据。

from pymongo import MongoClient
from bson import ObjectId

client = MongoClient(
    sample.com   # I hide my MongoDB account in here for security reason
)

db = client.Peter

user = db['User']
tx = db['Transaction']

db.User.drop()
db.Transaction.drop()

# Create
creative = [{'name': 'Peter', 'balance': 52642},
            {'name': 'Mary', 'balance': 57127},
            {'name': 'John', 'balance': 9000},
            {'name': 'Terry', 'balance': 29000},
            {'name': 'Tom', 'balance': 350000},
            {'name': 'Jason', 'balance': 21000},
            {'name': 'Ken', 'balance': 41400},
            {'name': 'Eva', 'balance': 21600}]

fake_record = [{'name': 'Peter', 'Transaction Type': 'Revenue', 'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Mary', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Mary', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'John', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'John', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'John', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Terry', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Terry', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Terry', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Terry', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Tom', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Tom', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Tom', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Jason', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Jason', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Jason', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Ken', 'Transaction Type': 'Revenue',
                   'Transaction Category': 'Food', 'Transaction amount': 52642},
               {'name': 'Eva', 'Transaction Type': 'Revenue', 'Transaction Category': 'Food', 'Transaction amount': 52642}]

db.User.insert_many(creative)
db.Transaction.insert_many(fake_record)

第2部分,下面的文件是我的主程序。

from database import user, tx
import getpass
import inquirer
import time
from view import View
from store import Store


def main():
    print("Welcome to The Goldman Sachs Group Banking System !!!")
    p = getpass .getpass("Please enter your password : ")
    if (p == 'sunday'):
        view1 = View()
        view1.first_page()


if __name__ == '__main__':
    main()

第3部分,下面的代码是我的视图程序,它包含了我所有的屏幕(页面)。如果此程序的用户 运行 此程序,他们将浏览下面的一些页面,我会让他们 select 我提供给他们的一些选项。

import inquirer
import time
from model import Player
from database import user, tx
from store import Store
import route


class View:
    def __init__(self) -> None:
        self.player = Player()
        self.route = route.Route()
        self.store = Store()

    def first_page(self) -> None:
        # Question Section
        questions = [
            inquirer.List('page_1_result',
                          message="What do you want to do?",
                          choices=['Continue With Existing User',
                                   'Create New Player'],
                          ),
        ]
        answer = inquirer.prompt(questions)

        # Answer Section
        if answer['page_1_result'] == 'Continue With Existing User':
            self.current_user = self.player.enterOldPlayers()
        else:
            self.current_user = self.player.createNewPlayer()
        self.store.setUserName(self.current_user)
        # Routing
        self.route.goTo1()

    def second_page(self):
        # Question Section
        print(f"Hello {str(self.store.getUserName())},\n")
        questions = [
            inquirer.List('Please Choose Action',
                          message=f"What do you want to do?",
                          choices=['View all transaction',
                                   'Add Tansaction',
                                   'Back to previous page'],
                          ),
        ]
        answer1 = inquirer.prompt(questions)

        # Answer Section
        if answer1['Please Choose Action'] == 'Add Tansaction':
            self.route.goTo("Page 3 c1")
        elif answer1['Please Choose Action'] == 'View all transaction':
            self.route.goTo("Page 4")
        else:
            self.route.goTo("Page 1")

    def third_page(self):
        questions = [
            inquirer.List('Please Choose a type',
                          message="Please Choose a type",
                          choices=['Revenue',
                                   'Expense',
                                   'Back to previous page'],
                          ),
        ]
        self.transaction_type = answer1 = inquirer.prompt(questions)
        # Back to second page if they chosen this answer
        if answer1['Please Choose a type'] == 'Back to previous page':
            self.route.goTo("Page 2")
        self.route.goTo("Page 3__v2")

    def third_page_v2(self):
        questions = [
            inquirer.List('Please Choose a category',
                          message="Please Choose a category",
                          choices=['Food',
                                   'Transportation',
                                   'Rent',
                                   'Back to previous page'],
                          ),
        ]
        self.transaction_category = answer1 = inquirer.prompt(questions)
        if answer1['Please Choose a category'] == 'Back to previous page':
            self.route.goTo("Page 3")
        else:
            self.route.goTo("Page 3__v3")

    def third_page_v3(self):
        self.amount = float(
            input('Please enter a amount for the transaction:'))
        if self.amount != '':
            self.route.goTo("Page 3__v4")

    def third_page_v4(self):
        dummy1 = user.find_one({'name': self.store.getUserName()})
        questions = [
            inquirer.List('Confirm',
                          message="Did you confirmed all the data inputed is correct?",
                          choices=['Yes',
                                   'No, bring me back to the previous page', ]
                          ),
        ]
        answer1 = inquirer.prompt(questions)
        if answer1['Confirm'] == 'Yes':
            tx.insert_one(
                # transaction_type['Please Choose a type'] << This line was used to obtained the value
                {'name': dummy1['name'],
                    'Transaction Type': self.transaction_type['Please Choose a type'],
                    'Transaction Category': self.transaction_category['Please Choose a category'],
                    'Transaction Amount': self.amount}
            )
            # Update Balance
            balance = dummy1['balance']
            if self.transaction_type['Please Choose a type'] == 'Revenue':
                balance += self.amount
                user.update_one({'name': dummy1['name']}, {
                                "$set": {'balance': (balance)}})
            else:
                balance -= self.amount
                user.update_one({'name': dummy1['name']}, {
                                "$set": {'balance': (balance)}})
                # TODO: ADD A {} in that set of data
            print(
                f"You have entered a entry with ---> {self.transaction_type['Please Choose a type']}, {self.transaction_category['Please Choose a category']}, {self.amount}")

            print("The database has been updated, you will be sent to the first page")
            time.sleep(1.5)
            self.route.goTo("Page 1")
        else:
            self.route.goTo("Page 3__v2")

    def fourth_page(self):
        transactions = tx.find({'name': self.store.getUserName()})
        for transaction in transactions:
            print(transaction)
        print("All transaction has been shown from the database.")
        time.sleep(1.5)
        questions = [
            inquirer.List('back_or_not',
                          message="Do you want to go back to previous page?",
                          choices=['Yes',
                                   'No, bring me back to the first page', ]
                          ),
        ]
        answer1 = inquirer.prompt(questions)
        self.go_back_or_not = answer1
        if self.go_back_or_not['back_or_not'] == 'Yes':
            self.route.goTo("Page 2")
        else:
            self.route.goTo("Page 1")

第4部分,下面的代码是我的路线,它告诉这个程序的用户如果运行这个程序会去哪个页面。

import view


class Route:

    def goTo(self, temp):
        if temp == "Page 2":
            self.user1 = view.View().current_user
            self.screen = view.View().second_page()
            return self.screen

        if temp == "Page 3":
            self.transaction_type = view.View().third_page()
            return self.transaction_type

        if temp == "Page 4":
            self.go_back_or_not = view.View().fourth_page()
            return self.go_back_or_not

        if temp == "Page 1":
            self.screen = view.View().first_page()
            return self.screen

        if temp == "Page 3__v2":
            self.transaction_category = view.View().third_page_v2()
            return self.transaction_category

        if temp == "Page 3__v3":
            self.screen = view.View().third_page_v3()
            return self.screen

        if temp == "Page 3__v4":
            self.screen = view.View().third_page_v4()
            return self.screen

    def goTo1(self):
        self.screen = view.View().second_page()
        return self.screen

第五部分,下面的代码称为模型。就是让用户在运行这个程序的时候决定是“使用旧播放器”还是“创建新用户”。这部分只是一个简单的功能。

from database import user, tx
import inquirer


class Player:
    def createNewPlayer(self):
        balance = 0
        name = str(input('Please enter a name for the new user:').capitalize())
        balance = float(
            input('Please enter a balance amount for the new User:'))
        new_user = {"name": name, "balance": balance}

        user.insert_one(new_user)
        return name

    def enterOldPlayers(self):
        users = user.find().sort("name")
        questions = [
            inquirer.List('user_selected',
                          message="Select a User",
                          choices=[user['name'] for user in users]
                          ),
        ]
        answer1 = inquirer.prompt(questions)
        return answer1['user_selected']

第 6 部分,下面的代码称为商店。我希望这部分充当服务器。如果用户输入一些变量。我想在这里保存所有变量。每当我想回调那些变量时,我都可以调用这部分的所有变量。

例如,当用户运行此程序时,他们需要select一个播放器(即一个帐户)。然后我想保存他们 selected 的帐户名称,并在这个程序的每一页打印他们的名字。

class Store:
    def __init__(self) -> None:
        pass

    def setUserName(self, username):
        self.username = username

    def getUserName(self):
        return self.username

问题来了:当我尝试运行 App.py(我程序的主要部分)时,它显示“AttributeError: 'Store' object has no attribute 'username'”在名为“Store”的文件中,这是第 6 部分中的代码。即“getUserNamereturn self.username”中的第 9 行。

我有点明白为什么会出现这个错误。这可能是因为当我在“self.store = Store()”行中 运行 我的代码的第 3 部分中的代码时,我已经清除了我存储的变量。

因为我故意把一个很大的文件分成多个文件,就像这些例子一样。 如果我想保留我现有的这六部分文件,我应该怎么做才能解决这个问题?

我知道在Java脚本中,有一个叫做“状态管理”的系统可以解决这个问题。但是在Python.

中不知道怎么解决

非常感谢!

最好在 class 的 __init__ 方法中设置任何 class 属性。

如果您不这样做,并在设置之前引用该属性,您将得到一个 AttributeError

这段代码比较安全;如果您尝试在设置用户名之前获取用户名,它将 return None,这是您尚未设置用户名的重要线索。

class Store:
    def __init__(self) -> None:
        self.username = None

    def setUserName(self, username):
        self.username = username

    def getUserName(self):
        return self.username