當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Django cached_property用法及代碼示例

本文介紹 django.utils.functional.cached_property 的用法。

聲明

class cached_property(func, name=None)[source]

@cached_property 裝飾器使用單個 self 參數作為屬性緩存方法的結果。隻要實例存在,緩存的結果就會一直存在,因此如果傳遞了實例並且隨後調用了函數,則將返回緩存的結果。

考慮一個典型情況,在將模型實例放入上下文之前,視圖可能需要調用模型的方法來執行一些計算,其中模板可能會再次調用該方法:

# the model
class Person(models.Model):

    def friends(self):
        # expensive computation
        ...
        return friends

# in the view:
if person.friends():
    ...

在模板中,您將擁有:

{% for friend in person.friends %}

在這裏,friends() 將被調用兩次。由於視圖中的實例person和模板是一樣的,用@cached_property裝飾friends()方法可以避免這種情況:

from django.utils.functional import cached_property

class Person(models.Model):

    @cached_property
    def friends(self):
        ...

請注意,由於該方法現在是一個屬性,因此在 Python 代碼中需要適當地訪問它:

# in the view:
if person.friends:
    ...

緩存的值可以視為實例的普通屬性:

# clear it, requiring re-computation next time it's called
del person.friends # or delattr(person, "friends")

# set a value manually, that will persist on the instance until cleared
person.friends = ["Huckleberry Finn", "Tom Sawyer"]

由於說明符協議的工作方式,在尚未訪問的 cached_property 上使用 del (或 delattr )會引發 AttributeError

除了提供潛在的性能優勢之外,@cached_property 還可以確保屬性的值在實例的生命周期內不會發生意外變化。這可能發生在計算基於 datetime.now() 的方法上,或者如果在同一實例上後續調用方法之間的短暫間隔內某個其他進程將更改保存到數據庫中。

您可以製作方法的緩存屬性。例如,如果您有一個昂貴的 get_friends() 方法並且希望允許在不檢索緩存值的情況下調用它,您可以編寫:

friends = cached_property(get_friends)

雖然 person.get_friends() 將在每次調用時重新計算好友,但緩存屬性的值將持續存在,直到您將其刪除,如上所述:

x = person.friends         # calls first time
y = person.get_friends()   # calls again
z = person.friends         # does not call
x is z                     # is True

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.utils.functional.cached_property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。