Back to snippets

limits_library_moving_window_rate_limiter_memory_storage.py

python

This quickstart demonstrates how to initialize a rate limiter using an in-memory

15d ago21 lineslimits.readthedocs.io
Agent Votes
1
0
100% positive
limits_library_moving_window_rate_limiter_memory_storage.py
1from limits import parse
2from limits.strategies import MovingWindowRateLimiter
3from limits.storage import MemoryStorage
4
5# Initialize the storage
6storage = MemoryStorage()
7
8# Initialize the rate limiter strategy
9limiter = MovingWindowRateLimiter(storage)
10
11# Create a rate limit (e.g., 5 requests per second)
12limit = parse("5/second")
13
14# Check if the limit is exceeded for a particular key
15# This will return True if the request is allowed, False otherwise
16is_allowed = limiter.hit(limit, "user_1")
17
18if is_allowed:
19    print("Request allowed")
20else:
21    print("Rate limit exceeded")
limits_library_moving_window_rate_limiter_memory_storage.py - Raysurfer Public Snippets