mirror of
https://github.com/GSA/notifications-api.git
synced 2026-02-04 02:11:11 -05:00
Implemented the rate limiting from Redis
- Uses Redis cache to check for current count - If not present then sets the value based on the database state - Any Redis errors are swallowed. Cache failures should NOT fail the request.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def cache_key(service_id):
|
||||
return "{}-{}-{}".format(str(service_id), datetime.utcnow().strftime("%Y-%m-%d"), "count")
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from flask.ext.redis import FlaskRedis
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class RedisClient:
|
||||
active = False
|
||||
redis_store = FlaskRedis()
|
||||
active = False
|
||||
|
||||
def init_app(self, app):
|
||||
self.active = app.config.get('REDIS_ENABLED')
|
||||
@@ -11,10 +12,30 @@ class RedisClient:
|
||||
if self.active:
|
||||
self.redis_store.init_app(app)
|
||||
|
||||
def set(self, key, value):
|
||||
def set(self, key, value, ex=None, px=None, nx=False, xx=False, raise_exception=False):
|
||||
if self.active:
|
||||
self.redis_store.set(key, value)
|
||||
try:
|
||||
self.redis_store.set(key, value, ex, px, nx, xx)
|
||||
except Exception as e:
|
||||
current_app.logger.exception(e)
|
||||
if raise_exception:
|
||||
raise e
|
||||
|
||||
def get(self, key):
|
||||
def inc(self, key, raise_exception=False):
|
||||
if self.active:
|
||||
self.redis_store.get(key)
|
||||
try:
|
||||
return self.redis_store.inc(key)
|
||||
except Exception as e:
|
||||
current_app.logger.exception(e)
|
||||
if raise_exception:
|
||||
raise e
|
||||
|
||||
def get(self, key, raise_exception=False):
|
||||
if self.active:
|
||||
try:
|
||||
return self.redis_store.get(key)
|
||||
except Exception as e:
|
||||
current_app.logger.exception(e)
|
||||
if raise_exception:
|
||||
raise e
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user