Pythonデコレータ:スロットル

By hientd, at: 2023年10月10日12:00

Estimated Reading Time: __READING_TIME__ minutes

[Python Decorators] Throttle
[Python Decorators] Throttle

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

 

説明

 

  1. @throttle(seconds): このデコレータは、関数の呼び出しを指定した秒数ごとに1回に制限します。
     
  2. last_called: スロットルを適用するために、関数が最後に呼び出された時間を追跡します。

 

利点

 

  • レート制限: 関数が頻繁に呼び出されるのを防ぎ、リソースを保護します。
     
  • 制御: リソースを大量に消費する関数がシステムをオーバーロードしないようにします。

 

ユースケース

 

  • APIリクエスト: APIのレート制限に準拠するために、リクエストのレートを制限します。
     
  • リソース管理: 大量の計算やデータベース操作を実行する関数のアクセスを制御します。

 

結論

 

throttleデコレータは、関数の呼び出し頻度を管理し、アプリケーションが効率的でレート制限に準拠した状態を維持するために役立つツールです。

その他のPythonデコレータについては、こちらをご覧ください。

 

Tag list:
- Decorator
- Logging Decorator
- Decorators Order
- Python decorators
- rate limit
- python throttle
- throttle
- throttling
- throttle decorators
- throttling rate limit
- throttle python

Related

Great Sites Website Review

Read more
Python

Read more
AI Great Sites

Read more

Subscribe

Subscribe to our newsletter and never miss out lastest news.