API

Storage

Abstract storage class

class limits.storage.Storage(uri=None, **options)[source]

Bases: object

Base class to extend when implementing a storage backend.

abstract check()[source]

check if storage is healthy

abstract clear(key)[source]

resets the rate limit key :param str key: the key to clear rate limits for

abstract get(key)[source]
Parameters

key (str) – the key to get the counter value for

abstract get_expiry(key)[source]
Parameters

key (str) – the key to get the expiry for

abstract incr(key, expiry, elastic_expiry=False)[source]

increments the counter for a given rate limit key

Parameters
  • key (str) – the key to increment

  • expiry (int) – amount in seconds for the key to expire in

  • elastic_expiry (bool) – whether to keep extending the rate limit window every hit.

abstract reset()[source]

reset storage to clear limits

Backend Implementations

In-Memory

class limits.storage.MemoryStorage(uri=None, **_)[source]

Bases: limits.storage.base.Storage

rate limit storage using collections.Counter as an in memory storage for fixed and elastic window strategies, and a simple list to implement moving window strategy.

acquire_entry(key, limit, expiry, no_add=False)[source]
Parameters
  • key (str) – rate limit key to acquire an entry in

  • limit (int) – amount of entries allowed

  • expiry (int) – expiry of the entry

  • no_add (bool) – if False an entry is not actually acquired but instead serves as a ‘check’

Return type

bool

check()[source]

check if storage is healthy

clear(key)[source]
Parameters

key (str) – the key to clear rate limits for

get(key)[source]
Parameters

key (str) – the key to get the counter value for

get_expiry(key)[source]
Parameters

key (str) – the key to get the expiry for

get_moving_window(key, limit, expiry)[source]

returns the starting point and the number of entries in the moving window

Parameters
  • key (str) – rate limit key

  • expiry (int) – expiry of entry

Returns

(start of window, number of acquired entries)

get_num_acquired(key, expiry)[source]

returns the number of entries already acquired

Parameters
  • key (str) – rate limit key to acquire an entry in

  • expiry (int) – expiry of the entry

incr(key, expiry, elastic_expiry=False)[source]

increments the counter for a given rate limit key

Parameters
  • key (str) – the key to increment

  • expiry (int) – amount in seconds for the key to expire in

  • elastic_expiry (bool) – whether to keep extending the rate limit window every hit.

reset()[source]

reset storage to clear limits

Redis

class limits.storage.RedisStorage(uri, **options)[source]

Bases: limits.storage.redis.RedisInteractor, limits.storage.base.Storage

Rate limit storage with redis as backend.

Depends on the redis-py library.

Parameters
  • uri (str) – uri of the form redis://[:password]@host:port, redis://[:password]@host:port/db, rediss://[:password]@host:port, redis+unix:///path/to/sock etc. This uri is passed directly to redis.from_url() except for the case of redis+unix where it is replaced with unix.

  • options – all remaining keyword arguments are passed directly to the constructor of redis.Redis

Raises

ConfigurationError – when the redis library is not available

acquire_entry(key, limit, expiry, no_add=False)[source]
Parameters
  • key (str) – rate limit key to acquire an entry in

  • limit (int) – amount of entries allowed

  • expiry (int) – expiry of the entry

  • no_add (bool) – if False an entry is not actually acquired but instead serves as a ‘check’

Returns

True/False

check()[source]

check if storage is healthy

clear(key)[source]
Parameters

key (str) – the key to clear rate limits for

get(key)[source]
Parameters

key (str) – the key to get the counter value for

get_expiry(key)[source]
Parameters

key (str) – the key to get the expiry for

incr(key, expiry, elastic_expiry=False)[source]

increments the counter for a given rate limit key

Parameters
  • key (str) – the key to increment

  • expiry (int) – amount in seconds for the key to expire in

reset()[source]

This function calls a Lua Script to delete keys prefixed with ‘LIMITER’ in block of 5000.

Warning

This operation was designed to be fast, but was not tested on a large production based system. Be careful with its usage as it could be slow on very large data sets.

Redis Cluster

class limits.storage.RedisClusterStorage(uri, **options)[source]

Bases: limits.storage.redis.RedisStorage

Rate limit storage with redis cluster as backend

Depends on redis-py-cluster library

Parameters
  • uri (str) – url of the form redis+cluster://[:password]@host:port,host:port

  • options – all remaining keyword arguments are passed directly to the constructor of rediscluster.RedisCluster

Raises

ConfigurationError – when the rediscluster library is not available or if the redis host cannot be pinged.

reset()[source]

Redis Clusters are sharded and deleting across shards can’t be done atomically. Because of this, this reset loops over all keys that are prefixed with ‘LIMITER’ and calls delete on them, one at a time.

Warning

This operation was not tested with extremely large data sets. On a large production based system, care should be taken with its usage as it could be slow on very large data sets

Redis Sentinel

class limits.storage.RedisSentinelStorage(uri, service_name=None, **options)[source]

Bases: limits.storage.redis.RedisStorage

Rate limit storage with redis sentinel as backend

Depends on redis-py library

Parameters
  • uri (str) – url of the form redis+sentinel://host:port,host:port/service_name

  • service_name, optional (str) – sentinel service name (if not provided in uri)

  • options – all remaining keyword arguments are passed directly to the constructor of redis.sentinel.Sentinel

Raises

ConfigurationError – when the redis library is not available or if the redis master host cannot be pinged.

check()[source]

check if storage is healthy

get(key)[source]
Parameters

key (str) – the key to get the counter value for

get_expiry(key)[source]
Parameters

key (str) – the key to get the expiry for

Memcached

class limits.storage.MemcachedStorage(uri, **options)[source]

Bases: limits.storage.base.Storage

Rate limit storage with memcached as backend.

Depends on the pymemcache library.

Parameters
  • uri (str) – memcached location of the form memcached://host:port,host:port, memcached:///var/tmp/path/to/sock

  • options – all remaining keyword arguments are passed directly to the constructor of pymemcache.client.base.Client

Raises

ConfigurationError – when pymemcache is not available

check()[source]

check if storage is healthy

clear(key)[source]
Parameters

key (str) – the key to clear rate limits for

get(key)[source]
Parameters

key (str) – the key to get the counter value for

get_client(module, hosts, **kwargs)[source]

returns a memcached client. :param module: the memcached module :param hosts: list of memcached hosts :return:

get_expiry(key)[source]
Parameters

key (str) – the key to get the expiry for

incr(key, expiry, elastic_expiry=False)[source]

increments the counter for a given rate limit key

Parameters
  • key (str) – the key to increment

  • expiry (int) – amount in seconds for the key to expire in

  • elastic_expiry (bool) – whether to keep extending the rate limit window every hit.

property storage

lazily creates a memcached client instance using a thread local

Google App Engine Memcached

class limits.storage.GAEMemcachedStorage(uri, **options)[source]

Bases: limits.storage.memcached.MemcachedStorage

rate limit storage with GAE memcache as backend

Parameters
  • uri (str) – memcached location of the form memcached://host:port,host:port, memcached:///var/tmp/path/to/sock

  • options – all remaining keyword arguments are passed directly to the constructor of pymemcache.client.base.Client

Raises

ConfigurationError – when pymemcache is not available

check()[source]

check if storage is healthy

incr(key, expiry, elastic_expiry=False)[source]

increments the counter for a given rate limit key

Parameters
  • key (str) – the key to increment

  • expiry (int) – amount in seconds for the key to expire in

  • elastic_expiry (bool) – whether to keep extending the rate limit window every hit.

Utility Methods

limits.storage.storage_from_string(storage_string, **options)[source]

factory function to get an instance of the storage class based on the uri of the storage

Parameters

storage_string – a string of the form method://host:port

Returns

an instance of flask_limiter.storage.Storage

Strategies

class limits.strategies.RateLimiter(storage)[source]

Bases: object

abstract get_window_stats(item, *identifiers)[source]

returns the number of requests remaining and reset of this limit.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

tuple (reset time (int), remaining (int))

abstract hit(item, *identifiers)[source]

creates a hit on the rate limit and returns True if successful.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

abstract test(item, *identifiers)[source]

checks the rate limit and returns True if it is not currently exceeded.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

class limits.strategies.FixedWindowRateLimiter(storage)[source]

Bases: limits.strategies.RateLimiter

Reference: Fixed Window

get_window_stats(item, *identifiers)[source]

returns the number of requests remaining and reset of this limit.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

tuple (reset time (int), remaining (int))

hit(item, *identifiers)[source]

creates a hit on the rate limit and returns True if successful.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

test(item, *identifiers)[source]

checks the rate limit and returns True if it is not currently exceeded.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

class limits.strategies.FixedWindowElasticExpiryRateLimiter(storage)[source]

Bases: limits.strategies.FixedWindowRateLimiter

Reference: Fixed Window with Elastic Expiry

hit(item, *identifiers)[source]

creates a hit on the rate limit and returns True if successful.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

class limits.strategies.MovingWindowRateLimiter(storage)[source]

Bases: limits.strategies.RateLimiter

Reference: Moving Window

get_window_stats(item, *identifiers)[source]

returns the number of requests remaining within this limit.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

tuple (reset time (int), remaining (int))

hit(item, *identifiers)[source]

creates a hit on the rate limit and returns True if successful.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

test(item, *identifiers)[source]

checks the rate limit and returns True if it is not currently exceeded.

Parameters
  • item – a RateLimitItem instance

  • identifiers – variable list of strings to uniquely identify the limit

Returns

True/False

Rate Limits

Rate limit granularities

class limits.RateLimitItem(amount, multiples=1, namespace='LIMITER')[source]

Bases: object

defines a Rate limited resource which contains the characteristic namespace, amount and granularity multiples of the rate limiting window.

Parameters
  • amount (int) – the rate limit amount

  • multiples (int) – multiple of the ‘per’ granularity (e.g. ‘n’ per ‘m’ seconds)

  • namespace (string) – category for the specific rate limit

classmethod check_granularity_string(granularity_string)[source]

checks if this instance matches a granularity string of type ‘n per hour’ etc.

Returns

True/False

get_expiry()[source]
Returns

the size of the window in seconds.

key_for(*identifiers)[source]
Parameters

identifiers – a list of strings to append to the key

Returns

a string key identifying this resource with each identifier appended with a ‘/’ delimiter.

class limits.RateLimitItemPerYear(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per year rate limited resource.

class limits.RateLimitItemPerMonth(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per month rate limited resource.

class limits.RateLimitItemPerDay(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per day rate limited resource.

class limits.RateLimitItemPerHour(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per hour rate limited resource.

class limits.RateLimitItemPerMinute(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per minute rate limited resource.

class limits.RateLimitItemPerSecond(amount, multiples=1, namespace='LIMITER')[source]

Bases: limits.limits.RateLimitItem

per second rate limited resource.

Utility Methods

limits.parse(limit_string)[source]

parses a single rate limit in string notation (e.g. ‘1/second’ or ‘1 per second’

Parameters

limit_string (string) – rate limit string using Rate limit string notation

Raises

ValueError – if the string notation is invalid.

Returns

an instance of RateLimitItem

limits.parse_many(limit_string)[source]

parses rate limits in string notation containing multiple rate limits (e.g. ‘1/second; 5/minute’)

Parameters

limit_string (string) – rate limit string using Rate limit string notation

Raises

ValueError – if the string notation is invalid.

Returns

a list of RateLimitItem instances.

Exceptions

exception limits.errors.ConfigurationError[source]

Bases: Exception

exception raised when a configuration problem is encountered