Skip to content

Currency Mixin

CurrencyExchangeMixin

The CurrencyExchangeMixin class enabled plugins to provide custom backends for updating currency exchange rate information.

Any implementing classes must provide the update_exchange_rates method.

Builtin Plugin

The default builtin plugin for handling currency exchange rates is the InvenTreeCurrencyExchangePlugin class.

Default InvenTree plugin for currency exchange rates.

Fetches exchange rate information from frankfurter.app

Source code in src/backend/InvenTree/plugin/builtin/integration/currency_exchange.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class InvenTreeCurrencyExchange(APICallMixin, CurrencyExchangeMixin, InvenTreePlugin):
    """Default InvenTree plugin for currency exchange rates.

    Fetches exchange rate information from frankfurter.app
    """

    NAME = 'InvenTreeCurrencyExchange'
    SLUG = 'inventreecurrencyexchange'
    AUTHOR = _('InvenTree contributors')
    TITLE = _('InvenTree Currency Exchange')
    DESCRIPTION = _('Default currency exchange integration')
    VERSION = '1.0.0'

    def update_exchange_rates(self, base_currency: str, symbols: list[str]) -> dict:
        """Request exchange rate data from external API."""
        response = self.api_call(
            'latest',
            url_args={'from': [base_currency], 'to': symbols},
            simple_response=False,
        )

        if response.status_code == 200:
            rates = response.json().get('rates', {})
            rates[base_currency] = 1.00

            return rates
        logger.warning(
            'Failed to update exchange rates from %s: Server returned status %s',
            self.api_url,
            response.status_code,
        )
        return {}

    @property
    def api_url(self):
        """Return the API URL for this plugin."""
        return 'https://api.frankfurter.app'

Sample Plugin

A simple example is shown below (with fake data).

from plugin import InvenTreePlugin
from plugin.mixins import CurrencyExchangeMixin

class MyFirstCurrencyExchangePlugin(CurrencyExchangeMixin, InvenTreePlugin):
    """Sample currency exchange plugin"""

    ...

    def update_exchange_rates(self, base_currency: str, symbols: list[str]) -> dict:
        """Update currency exchange rates.

        This method *must* be implemented by the plugin class.

        Arguments:
            base_currency: The base currency to use for exchange rates
            symbols: A list of currency symbols to retrieve exchange rates for

        Returns:
            A dictionary of exchange rates, or None if the update failed

        Raises:
            Can raise any exception if the update fails
        """

        rates = {
            'base_currency': 1.00
        }

        for sym in symbols:
            rates[sym] = random.randrange(5, 15) * 0.1

        return rates