"""Physical reserves model. Physical reserves are stored in Snowflake """ import json from redis import RedisError from ows_accounting import response from ows_accounting.connectors import redis, snowflake from ows_accounting.models.sql import physical_reserves from ows_accounting.utils import sentry def _get_key(vendor_id, period_id): """Get generated key for cache. Args: vendor_id (int): Account Id period_id (int): Accounting period Id Returns: string: Key for cache record identifier """ return 'reserves:{account_id}:{period_id}'.format( account_id=str(vendor_id), period_id=str(period_id) ) def _set_cache(vendor_id, period_id, data): """Cache physical reserves response.""" try: redis.client.set( _get_key(vendor_id, period_id), json.dumps(data) ) except RedisError: if sentry.sentry_client: sentry.sentry_client.captureException() def _get_cache(vendor_id, period_id): """Get cached physical reserves response.""" result = redis.client.get(_get_key(vendor_id, period_id)) if result: result = json.loads(result.decode('utf8')) return result def get(vendor_id, period_id): """Get physical reserves information. Args: vendor_id (int): Account Id period_id (int): active period id Returns: response.Response: Account revenue data or error response """ results = _get_cache(vendor_id, period_id) if not results: with snowflake.db_session() as session: results = session.execute( physical_reserves.SQL_GET_PHYSICAL_RESERVES, { 'vendor_id': vendor_id, 'period_id': period_id } ).fetchall() results = [ { 'reserve_taken_date': result[0], 'reserve_release_date': result[1], 'currency': result[2], 'amount': str(result[3]), 'period': str(result[4]) } for result in results ] if results: _set_cache(vendor_id, period_id, results) return response.Response(message=results)