""" Currency Model. Model for getting information about currency """ from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.exc import SQLAlchemyError from ows_accounting import response from ows_accounting.constants import error from ows_accounting.utils import mysql from ows_accounting.utils import sentry _cached_currencies = [] class Currency(mysql.BaseModel): """Class for currency model.""" __tablename__ = "currencies" currency_id = Column('id', Integer, primary_key=True, autoincrement=True) code = Column('ISO_4217_code', String(12)) symbol = Column('symbol_html_entity_code', String(45)) name = Column('currency_name', String(45)) def as_dict(self): """Return object as dict. Returns dict: Dictionary representation of the object """ currency_dict = { 'id': self.currency_id, 'code': self.code, 'symbol': self.symbol, 'name': self.name } return currency_dict def _get_cached_currency_by_id(currency_id): """Get currency from cached list by id. Args: currency_id (int): Currency Id. Returns: Currency: currency model or None """ return next( (item for item in _cached_currencies if item['id'] == currency_id), None) def get_currency_by_id(currency_id): """Get currency by id. Args: currency_id (int): Currency Id. Returns: response.Response: Currency or error in Response object. """ currency = _get_cached_currency_by_id(currency_id) if currency: return response.Response(currency) try: with mysql.db_session(False) as session: currency = session.query(Currency).filter_by( currency_id=currency_id).first() if not currency: return response.create_not_found_response( error.ERROR_MESSAGE_CURRENCY_NOT_FOUND) _cached_currencies.append(currency.as_dict()) return response.Response(currency.as_dict()) except SQLAlchemyError as ex: if sentry.sentry_client: sentry.sentry_client.captureException() return response.create_fatal_response(str(ex))