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:
Martyn Inglis
2016-11-11 16:47:52 +00:00
parent 6c27f8023e
commit 88f04a46cf
8 changed files with 225 additions and 44 deletions

View File

@@ -206,7 +206,6 @@ def get_notification_statistics_for_day():
@notifications.route('/notifications/<string:notification_type>', methods=['POST'])
def send_notification(notification_type):
redis_store.set('key1', 'value')
if notification_type not in ['sms', 'email']:
assert False

View File

@@ -4,12 +4,19 @@ from app.dao import services_dao
from app.models import KEY_TYPE_TEST, KEY_TYPE_TEAM
from app.service.utils import service_allowed_to_send_to
from app.v2.errors import TooManyRequestsError, BadRequestError
from app import redis_store
from app.clients import redis
def check_service_message_limit(key_type, service):
if all((key_type != KEY_TYPE_TEST,
service.restricted)):
service_stats = services_dao.fetch_todays_total_message_count(service.id)
if key_type != KEY_TYPE_TEST:
cache_key = redis.cache_key(service.id)
service_stats = redis_store.get(cache_key)
if not service_stats:
service_stats = services_dao.fetch_todays_total_message_count(service.id)
redis_store.set(cache_key, service_stats, ex=3600)
print(service_stats)
print(service.message_limit)
if service_stats >= service.message_limit:
raise TooManyRequestsError(service.message_limit)