Implementing Backend Rate Limiting with a Python Decorator

To prevent excessive user actions such as rapid screenshot requests, this guide shows how to implement a backend rate‑limiting mechanism using a reusable Python decorator that enforces a default 0.3‑second interval, handling exceptions when the limit is exceeded.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Implementing Backend Rate Limiting with a Python Decorator

When building web products, certain features must restrict how frequently a user can perform actions to prevent malicious attacks, and both frontend and backend need such controls to avoid bypassing frontend limits.

For example, a testing platform that rents real devices may need to limit how often a user can take screenshots.

To satisfy the many backend endpoints that require frequency control, a Python decorator is introduced, offering easy extensibility and low modification cost.

The decorator defaults to a 0.3‑second interval, assuming typical user actions occur slower than that.

Decorator implementation:

"""
    seconds单位是秒
    需要捕获异常exceptions.FunctionFrequency
"""
def runFrequencyLimit(seconds=0.3):
    def call_func(fn):
        cache = {}
        @wraps(fn)
        def wrapper(*params, **paramMap):
            if fn.__name__ in cache:
                last_time  = cache[fn.__name__]
                if time.time() - last_time > seconds:
                    ret = fn(*params, **paramMap)
                    cache[fn.__name__] = time.time()
                    return ret
                else:
                    raise exceptions.FunctionFrequency()
            else:
                ret = fn(*params, **paramMap)
                cache[fn.__name__] = time.time()
                return ret
        return wrapper
    return call_func

Usage simply involves adding the decorator to the target function:

@runFrequencyLimit()
def handle_snapshot(self, *params, **paramMap):
    try:
        # screenshot operation omitted
    except exceptions.FunctionFrequency:
        print "操作过于频繁,请休息一下再试^_^"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

APIrate limitingDecorator
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.