Pythonデコレータ:スロットル
By hientd, at: 2023年10月10日12:00
Estimated Reading Time: __READING_TIME__ minutes
![[Python Decorators] Throttle](/media/filer_public_thumbnails/filer_public/70/13/70130ed7-d937-418f-9837-d87d485daabc/python_decorators_-_thottle.png__1500x900_crop_subsampling-2_upscale.png)
![[Python Decorators] Throttle](/media/filer_public_thumbnails/filer_public/70/13/70130ed7-d937-418f-9837-d87d485daabc/python_decorators_-_thottle.png__400x240_crop_subsampling-2_upscale.png)
Pythonのthrottle
デコレータは、関数の呼び出し頻度を制限するために使用されます。これは、関数が頻繁に呼び出されるのを防ぐためのレート制限に特に役立ち、APIとやり取りしたり、リソースを大量に消費するタスクを実行したりする関数にとって重要です。
NOTE: Django Rest Frameworkは、この機能を内部的に提供しています
実装
throttle
デコレータを実装する方法は次のとおりです。
import time
from functools import wraps
def throttle(seconds):
def decorator(func):
last_called = [0]
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
if elapsed >= seconds:
last_called[0] = time.time()
return func(*args, **kwargs)
else:
print("Function call throttled")
return wrapper
return decorator
@throttle(5)
def my_function():
print("Function called")
my_function() # 出力: Function called
time.sleep(2)
my_function() # 出力: Function call throttled
time.sleep(5)
my_function() # 出力: Function called
説明
- @throttle(seconds): このデコレータは、関数の呼び出しを指定した秒数ごとに1回に制限します。
- last_called: スロットルを適用するために、関数が最後に呼び出された時間を追跡します。
利点
- レート制限: 関数が頻繁に呼び出されるのを防ぎ、リソースを保護します。
- 制御: リソースを大量に消費する関数がシステムをオーバーロードしないようにします。
ユースケース
- APIリクエスト: APIのレート制限に準拠するために、リクエストのレートを制限します。
- リソース管理: 大量の計算やデータベース操作を実行する関数のアクセスを制御します。
結論
throttle
デコレータは、関数の呼び出し頻度を管理し、アプリケーションが効率的でレート制限に準拠した状態を維持するために役立つツールです。
その他のPythonデコレータについては、こちらをご覧ください。