File tree Expand file tree Collapse file tree 2 files changed +95
-1
lines changed Expand file tree Collapse file tree 2 files changed +95
-1
lines changed Original file line number Diff line number Diff line change @@ -280,7 +280,7 @@ Python Notes 學習筆記 📝
280
280
281
281
[ colorama_tutorial.py] ( https://github.com/twtrubiks/python-notes/tree/master/colorama_tutorial.py ) - 讓 python 輸出 terminal 有顏色
282
282
283
- [ marshmallow_tutorial ] ( https://github.com/twtrubiks/python-notes/tree/master/marshmallow_tutorial ) - 序列化, 反序列化, 驗證資料格式
283
+ [ cachetools_tutorial.py ] ( https://github.com/twtrubiks/python-notes/tree/master/cachetools_tutorial.py ) - cachetools 教學
284
284
285
285
## 觀念
286
286
Original file line number Diff line number Diff line change
1
+ """
2
+ pip3 install cachetools
3
+
4
+ https://pypi.org/project/cachetools/
5
+ """
6
+
7
+ from cachetools import cached , LRUCache , TTLCache
8
+ import time
9
+
10
+ @cached (cache = {})
11
+ def ex1_cache ():
12
+ print ('no cached' )
13
+ return 'my data'
14
+
15
+ def ex1 ():
16
+ for _ in range (3 ):
17
+ print (ex1_cache ())
18
+
19
+ # 手動清理快取
20
+ # ex1_cache.cache_clear()
21
+
22
+ # for _ in range(3):
23
+ # print(ex1_cache())
24
+
25
+
26
+ @cached (LRUCache (maxsize = 10 ))
27
+ def ex2_cache (count ):
28
+ print ('no cached' )
29
+ return 'my data'
30
+
31
+ def ex2 ():
32
+ print ('step1...' )
33
+ for i in range (10 ):
34
+ # 這裡沒快取 因為第一次
35
+ print (ex2_cache (i ))
36
+
37
+ print ('step2...' )
38
+ for i in range (10 ):
39
+ # 這裡都有快取
40
+ print (ex2_cache (i ))
41
+
42
+ print ('step3...' )
43
+ for i in range (30 , 40 ):
44
+ # 快取開始失效, 因為超過 maxsize
45
+ print (ex2_cache (i ))
46
+
47
+
48
+ @cached (TTLCache (maxsize = 5 , ttl = 2 ))
49
+ def ex3_cache ():
50
+ print ('no cached' )
51
+ return 'my data'
52
+
53
+ def ex3 ():
54
+ for _ in range (5 ):
55
+ print (ex3_cache ())
56
+
57
+ time .sleep (3 )
58
+ # 快取失效
59
+
60
+ for _ in range (5 ):
61
+ print (ex3_cache ())
62
+
63
+ MY_CACHE = TTLCache (maxsize = 200 , ttl = 2 )
64
+
65
+ def set_cache ():
66
+ MY_CACHE ['1' ] = '1'
67
+ MY_CACHE ['2' ] = '2'
68
+ MY_CACHE ['3' ] = '3'
69
+
70
+ def get_cache ():
71
+ if MY_CACHE .get ('1' ):
72
+ print ('cached' )
73
+ print (MY_CACHE .get ('1' ))
74
+ else :
75
+ print ('no cached' )
76
+
77
+ def ex4 ():
78
+ set_cache ()
79
+
80
+ for _ in range (3 ):
81
+ get_cache ()
82
+
83
+ print ('查看目前 cache 狀態:' , dict (MY_CACHE ))
84
+ print ('sleep 2.5 sec' )
85
+ time .sleep (2.5 )
86
+
87
+ # cached expired
88
+ get_cache ()
89
+
90
+ if __name__ == '__main__' :
91
+ ex1 ()
92
+ # ex2()
93
+ # ex3()
94
+ # ex4()
You can’t perform that action at this time.
0 commit comments