Token Calculate / Exchange Rate

Exchange Rate Service

The ExchangeRateService class is responsible for managing US dollar exchange rates, combining the retrieval of up-to-date data from the Central Bank of Brazil (BCB) API with local storage of these records for future queries.

On this page

    #Overview

    The ExchangeRateService class is responsible for managing US dollar exchange rates, combining the retrieval of up-to-date data from the Central Bank of Brazil (BCB) API with local storage of these records for future queries. It keeps a limited history of rates to optimize the local database, avoiding excessive storage of old data.

    This service is useful for applications that need the up-to-date dollar rate, but also need to guarantee quick access to recent data even when the external API fails. By storing locally and limiting the data kept, the class provides an efficient and resilient solution for systems that depend on this information.

    In practice, the class can be used to obtain the real-time dollar rate, with automatic fallback to the last available value and persistence of the data for future queries.

    #Execution Flow

    1. An object of the ExchangeRateService class is instantiated.
    2. The get_usd_rate() method is called to obtain the dollar rate.
    3. The method checks whether a record of the day's rate already exists in the local database.
    4. If the day's record is already available, it returns that value straight from the database.
    5. If not, it queries the most recent rate from the BCB API.
    6. If the API returns a valid value:
      • The value is stored in the local database.
      • A rule is applied to limit the number of saved records (keeping up to 5 records).
      • The value is returned.
    7. If the API fails and there is previous data in the database, the last stored value is returned.
    8. If there is no data, a default base value is returned and this base is stored locally.
    9. The local database is always kept at a maximum of 5 records, removing the oldest ones when necessary.
    10. If an error occurs during the process, a RuntimeError is raised.

    #Class Methods Table

    MethodDescription
    __init__Initializes the service, configures the local database and dates.
    _get_bcb_rateFetches the most recent dollar rate from the BCB API.
    _get_last_db_recordGets the last record stored locally.
    _enforce_limitLimits the number of saved records, deleting the old ones.
    get_usd_rateGets the dollar rate with fallback and persistence.

    #Key Architecture Points and Insights

    • Design based on a robust fallback: The get_usd_rate method tries to prioritize up-to-date data, but gracefully handles failures of the external API by using local data or a default base.
    • Encapsulation: The use of private methods (_get_bcb_rate, _get_last_db_record, _enforce_limit) separates responsibilities inside the class, keeping the interface clean for the user.
    • History limit: Keeping a maximum number of records avoids uncontrolled growth of the local database, which is important for performance and space.
    • Integration with other classes: The class uses DocumentStore for local persistence and BCBExchangeRateService for integration with the external rate API, demonstrating composition and separation of responsibilities.
    • Use of a standardized date format: Dates are always stored and compared in the ISO format %Y-%m-%d, ensuring consistency.
    • Exception handling: General errors are caught and wrapped in a RuntimeError to signal failures specific to this service.

    #Class and Methods Description

    #ExchangeRateService Class

    #Description

    Class to manage US dollar exchange rates. It fetches rates from the Central Bank of Brazil API, stores the information locally, keeps a limited history of the data and offers access to the current rate with fallback mechanisms to guarantee service continuity even in case of external failures.

    #Methods

    #1. __init__

    Description

    Initializes the service instance, configuring the local database manager, setting a default rate base and storing the current formatted date.

    Arguments

    None.

    Returns

    Returns no value.

    Raises

    None.

    Examples

    service = ExchangeRateService()

    #2. _get_bcb_rate

    Description

    Retrieves the most recent dollar rate from the Central Bank of Brazil API using the BCBExchangeRateService service.

    Arguments

    None.

    Returns

    • float: Value of the most recent dollar rate obtained from the API.

    Raises

    None (assuming errors are handled externally).

    Examples

    rate = service._get_bcb_rate()
    print(rate)  # Exemplo esperado: 5.25

    #3. _get_last_db_record

    Description

    Fetches the most recent dollar rate record from the local database. Returns the record with the latest date, or None if there are no records.

    Arguments

    None.

    Returns

    • dict or None: Dictionary with the most recent record or None if the database is empty.

    Raises

    None.

    Examples

    last_record = service._get_last_db_record()
    if last_record:
        print(last_record["rate"])
    else:
        print("Nenhum registro encontrado.")

    #4. _enforce_limit

    Description

    Limits the maximum number of records saved in the local database to the specified value, removing the oldest records if the limit is exceeded.

    Arguments

    • limit (int): Maximum number of records allowed in the database. Default is 5.

    Returns

    Returns no value.

    Raises

    None.

    Examples

    service._enforce_limit(limit=5)
    # Garante que no banco existam no máximo 5 registros recentes.

    #5. get_usd_rate

    Description

    Gets the current US dollar rate. It first checks whether the day's rate is already saved in the local database; otherwise, it tries to fetch it from the BCB API. If the API returns data, it saves it locally while limiting the history. If the API fails, it returns the last saved value or a default base value. It handles general errors by raising RuntimeError.

    Arguments

    None.

    Returns

    • float: Current rate ready for use.

    Raises

    • RuntimeError: In case of a general failure in obtaining or storing the rate.

    Examples

    try:
        rate = service.get_usd_rate()
        print(f"Cotação do dólar: {rate}")
    except RuntimeError:
        print("Não foi possível obter a cotação.")
    
    # python -m src.tokens_calculate.exchange_rate

    #End of documentation.

    Source: src/tokens_calculate/exchange_rate/exchange_rate.py

    Esc
    ↑↓navigate Enteropen