~sirn/fanboi2

ref: c1f8e48d5062ca982c7bd9392477a4cc8623d32e fanboi2/fanboi2/utils/rate_limiter.py -rw-r--r-- 1.0 KiB
c1f8e48dKridsada Thanabulpong Fix GeoIP2 raising no method error. 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import hashlib
from .request import serialize_request
from ..models import redis_conn


class RateLimiter(object):
    """Rate limit to throttle content posting to every specific seconds."""

    def __init__(self, request, namespace=None):
        request = serialize_request(request)
        self.key = "rate:%s:%s" % (
            namespace,
            hashlib.md5(request['remote_addr'].encode('utf8')).hexdigest(),
        )

    def limit(self, seconds=10):
        """Mark user as rate limited for `seconds`.

        :param seconds: A number of seconds :type:`int` to rate limited for.

        :type seconds: int
        :rtype: None
        """
        redis_conn.set(self.key, 1)
        redis_conn.expire(self.key, seconds)

    def limited(self):
        """Returns true if content should be limited from posting.
        :rtype: bool
        """
        return redis_conn.exists(self.key)

    def timeleft(self):
        """Returns seconds left until user is no longer throttled.
        :rtype: int
        """
        return redis_conn.ttl(self.key)