Skip to content

Config

FIO Wrapper internally uses a configuration file to provide its standard capabilities. The configuration can be overwritten by the user.

base.yml

fio:
  application: FIO Wrapper
  version: 1.0.0
  base_url: https://rest.fnar.net
  timeout: 10
  ssl_verify: true
  versions:
    - 1.0.0
cache:
  enabled: false
  default_expire: 3600
fio_urls:
  1.0.0:
    material_base: /material
    material_all: /allmaterials
    exchange_base: /exchange
    exchange_orders: /orders
    exchange_all: /all
    exchange_full: /full
    building_base: /building
    building_all: /allbuildings
    recipe_base: /recipes
    recipe_all: /allrecipes
    planet_base: /planet
    planet_all: /allplanets
    planet_full: /allplanets/full
    planet_sites: /sites
    planet_search: /search
    localmarket_base: /localmarket
    localmarket_planet: /planet
    localmarket_shipping_source: /shipping/source
    localmarket_shipping_destination: /shipping/destination
    localmarket_company: /company
    sites_base: /sites
    sites_planets: /planets
    sites_warehouses: /warehouses
    storage_base: /storage
    storage_planets: /planets
    groups: /auth/groups
    groups_group: /auth/group
    groups_groupmemberships: /auth/groupmemberships
    groups_hub: /fioweb/grouphub
    groups_burn: /fioweb/burn/group

Config() class

logger module-attribute

logger = logging.getLogger(__name__)

Config

1
2
3
4
5
6
7
8
9
Config(
    api_key=None,
    version=None,
    application=None,
    base_url=None,
    timeout=10.0,
    ssl_verify=True,
    user_config=None,
)

FIO Wrapper configuration class

Attributes:

Name Type Description
_api_key str

FIO API key

_version str

FIO API version

_application str

Application name

_base_url str

FIO base url

_timeout float

FIO generic timeout

_ssl_verify bool

Request ssl verification

data ConfigParser

Configuration Parser

Initializes the configuration

Parameters:

Name Type Description Default
api_key Optional[str]

FIO API key. Defaults to None.

None
version Optional[str]

FIO API version. Defaults to None.

None
application Optional[str]

Application name. Defaults to None.

None
base_url Optional[str]

FIO base url. Defaults to None.

None
timeout Optional[float]

FIO generic timeout. Defaults to 10.0.

10.0
ssl_verify Optional[bool]

Request ssl verification. Defaults to True.

True
user_config Optional[str]

User configuration file. Defaults to None.

None
Source code in fio_wrapper/config.py
def __init__(
    self,
    api_key: Optional[str] = None,
    version: Optional[str] = None,
    application: Optional[str] = None,
    base_url: Optional[str] = None,
    timeout: Optional[float] = 10.0,
    ssl_verify: Optional[bool] = True,
    user_config: Optional[str] = None,
) -> None:
    """Initializes the configuration

    Args:
        api_key (Optional[str]): FIO API key. Defaults to None.
        version (Optional[str]): FIO API version. Defaults to None.
        application (Optional[str]): Application name. Defaults to None.
        base_url (Optional[str]): FIO base url. Defaults to None.
        timeout (Optional[float]): FIO generic timeout. Defaults to 10.0.
        ssl_verify (Optional[bool]): Request ssl verification. Defaults to True.
        user_config (Optional[str]): User configuration file. Defaults to None.
    """
    # FIO instantiation overwrites
    self._api_key = api_key
    self._version = version
    self._application = application
    self._base_url = base_url
    self._timeout = timeout
    self._ssl_verify = ssl_verify

    # initialize data
    self._base_file = os.path.join(os.path.dirname(__file__), "base.yml")

    # base configuration
    with open(self._base_file, "r") as base_file:
        self.data = yaml.safe_load(base_file)

    # user config, if provided
    if user_config is not None:
        with open(user_config, "r") as user_file:
            user = yaml.safe_load(user_file)

            # self.data = self.dict_merge(self.data, user)
            self.data = self.data_merge(self.data, user)

data instance-attribute

data = self.data_merge(self.data, user)

versions property

versions

Gets the versions information from config

Raises:

Type Description
SystemExit

No list of available FIO versions provided

Returns:

Type Description
List[str]

List[str]: List of versions

api_key property

api_key

Gets the FIO API key

Returns:

Name Type Description
str str

FIO API key or None

version property

version

Gets the FIO version specified

Returns:

Name Type Description
str str

FIO API version

application property

application

Gets the application name

Returns:

Name Type Description
str str

Application name

base_url property

base_url

Gets the FIO base url

Returns:

Name Type Description
str str

FIO base url

timeout property

timeout

Gets the timeout parameter

Returns:

Name Type Description
float float

Timeout parameter

ssl_verify property

ssl_verify

Gets the ssl verification parameter

Returns:

Name Type Description
float float

Seconds as float of request timeout

cache property

cache

Gets the cache usage status

Returns:

Name Type Description
bool bool

Cache used, true or false

cache_default_expire property

cache_default_expire

Gets the cache default expiration time

Returns:

Name Type Description
int int

Expiration time in seconds

data_merge

data_merge(a, b)

merges b into a and return merged result

Parameters:

Name Type Description Default
a Dict

First dictionary

required
b Dict

Second dictionary

required
NOTE

tuples and arbitrary objects are not handled as it is totally ambiguous what should happen

Source code in fio_wrapper/config.py
def data_merge(self, a, b):
    """merges b into a and return merged result

    Args:
        a (Dict): First dictionary
        b (Dict): Second dictionary

    NOTE:
        tuples and arbitrary objects are not handled as it is totally ambiguous what should happen
    """
    key = None
    # ## debug output
    # sys.stderr.write("DEBUG: %s to %s\n" %(b,a))

    if (
        a is None
        or isinstance(a, str)
        or isinstance(a, int)
        or isinstance(a, float)
    ):
        # border case for first run or if a is a primitive
        a = b
    elif isinstance(a, list):
        # lists can be only appended
        if isinstance(b, list):
            # merge lists
            a.extend(b)
        else:
            # append to list
            a.append(b)
    elif isinstance(a, dict):
        # dicts must be merged
        if isinstance(b, dict):
            for key in b:
                if key in a:
                    a[key] = self.data_merge(a[key], b[key])
                else:
                    a[key] = b[key]
        else:
            raise Exception('Cannot merge non-dict "%s" into dict "%s"' % (b, a))
    else:
        raise Exception('NOT IMPLEMENTED "%s" into "%s"' % (b, a))

    return a

get

get(section, option)

Gets a configuration element

Parameters:

Name Type Description Default
section str

Configuration section

required
option str

Configuration option

required

Raises:

Type Description
UnknownConfig

Configuration not found

Returns:

Name Type Description
str str

Configuration element

Source code in fio_wrapper/config.py
def get(self, section: str, option: str) -> str:
    """Gets a configuration element

    Args:
        section (str): Configuration section
        option (str): Configuration option

    Raises:
        UnknownConfig: Configuration not found

    Returns:
        str: Configuration element
    """
    logger.debug("get(): %s | %s", section, option)
    try:
        return self.data[section][option]
    except KeyError as exc:
        raise UnknownConfig() from exc

get_url

get_url(option)

Gets a url configuration element

Parameters:

Name Type Description Default
option str

Configuration option

required

Returns:

Name Type Description
str str

URL configuration parameter

Source code in fio_wrapper/config.py
def get_url(self, option: str) -> str:
    """Gets a url configuration element

    Args:
        option (str): Configuration option

    Returns:
        str: URL configuration parameter
    """

    try:
        return self.data["fio_urls"][self.version][option]
    except KeyError as exc:
        raise UnknownConfig() from exc

cache_url_expirations

cache_url_expirations()

Creates the dict for requests_cache url expirations

Returns:

Type Description
Dict[str, any]

Dict[str, any]: URL specific expiration settings

Source code in fio_wrapper/config.py
def cache_url_expirations(self) -> Dict[str, any]:
    """Creates the dict for requests_cache url expirations

    Returns:
        Dict[str, any]: URL specific expiration settings
    """
    # check if requests-cache is installed
    if not self.cache or importlib.util.find_spec("requests_cache") is None:
        return {}

    from requests_cache import DO_NOT_CACHE, NEVER_EXPIRE

    expiration_list = {}

    for url, expiration in self.data.get("cache", {}).get("urls", {}).items():
        if isinstance(expiration, int):
            expiration_list[url] = expiration
        elif expiration == "NEVER_EXPIRE":
            expiration_list[url] = NEVER_EXPIRE
        elif expiration == "DO_NOT_CACHE":
            expiration_list[url] = DO_NOT_CACHE
        else:
            logger.warning(
                "Unknown expiration configuration: %s | %s", url, expiration
            )

    return expiration_list