0

Case. I want to modify and add the following behavior to the code below (it's a context processor):

After checking if a user is authenticated check the last time the balance was updated (cookie maybe) if it was updated in the last 5 mins do nothing, else get the new balance as normal.

def get_balance(request):

     if request.user.is_authenticated():
        balance = Account.objects.get(user=request.user).balance
     else:
        balance = 0

     return {'account_balance': balance}

HOWEVER:

I want to learn a little more about OOP in Django/Python can some modify the example to achieve my goal include the use of:

Property: I come from Java, I want to set and get, it makes more sense to me. get balance if does not exist else create new one.

Constructor method: In Python I think I have to change this to a class and use init right?

UPDATE:

To use a construct I first think I need to create a class, I'm assuming this is ok using as a context processor in Django to do something like this:

class BalanceProcessor(request):

    _balance = Account.objects.get(user=request.user).balance

    @property
    def get_balance(self):
       return  return {'account_balance': _balance}

    @setter???
4

1 回答 1

2

Python不是 Java。在 Python 中,你不会无缘无故地创建类。类适用于您想要用代码封装的数据。在这种情况下,没有这样的事情:您只需获取一些数据并返回它。上课在这里毫无用处。

无论如何,即使您确实创建了一个类,Python 也不是 Java,并且您不会在属性上创建 getter 和 setter,除非您在获取和设置时确实需要进行一些处理。如果您只想访问一个实例属性,那么您只需访问它。

最后,由于两个原因,您提出的代码将不起作用。首先,您试图继承自request. 这是没有意义的:你应该继承自,object除非你是子类化的东西。其次,您希望如何实例化您的类?上下文处理器通常是函数,这意味着 Django 期待一个可调用的。如果您将类作为上下文处理器,那么调用它将实例化它:但是没有任何东西会调用该get_balance方法。并且您的代码将失败,因为 Django 将传递request到实例化中(正如它期望对函数所做的那样)并且您__init__不期望该参数。

在 Python 中试验类很好,但上下文处理器不适合它。

于 2013-06-19T10:45:28.687 回答