Example #1
0
def _get_token(creds, base_url):
    """Parse credentials and get token from IIASA authentication service"""
    plaintextcreds = True

    # try reading default config or parse file
    if creds is None:
        creds = _get_config()
        plaintextcreds = False
    elif isinstance(creds, Path) or isstr(creds):
        _creds = _get_config(creds)
        if _creds is None:
            logger.error(f"Could not read credentials from `{creds}`")
        creds = _creds
        plaintextcreds = False

    # if (still) no creds, get anonymous auth and return
    if creds is None:
        url = "/".join([base_url, "anonym"])
        r = requests.get(url)
        _check_response(r, "Could not get anonymous token")
        return r.json(), None

    # parse creds, write warning
    if isinstance(creds, Mapping):
        user, pw = creds["username"], creds["password"]
    else:
        user, pw = creds
    if plaintextcreds:
        logger.warning("You provided credentials in plain text. DO NOT save "
                       "these in a repository or otherwise post them online")
        deprecation_warning(
            "Please use `pyam.iiasa.set_config(<user>, <pwd>)`"
            " to store your credentials in a file!",
            "Providing credentials in plain text",
        )

    # get user token
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    data = {"username": user, "password": pw}
    url = "/".join([base_url, "login"])
    r = requests.post(url, headers=headers, data=json.dumps(data))
    _check_response(r, "Login failed for user: {}".format(user))
    return r.json(), user
Example #2
0
File: iiasa.py Project: gidden/pyam
def _get_token(creds, base_url):
    """Parse credentials and get token from IIASA authentication service"""
    plaintextcreds = True

    # try reading default config or parse file
    if creds is None:
        creds = _get_config()
        plaintextcreds = False
    elif isinstance(creds, Path) or isstr(creds):
        _creds = _get_config(creds)
        if _creds is None:
            logger.error(f'Could not read credentials from `{creds}`')
        creds = _creds
        plaintextcreds = False

    # if (still) no creds, get anonymous auth and return
    if creds is None:
        url = '/'.join([base_url, 'anonym'])
        r = requests.get(url)
        _check_response(r, 'Could not get anonymous token')
        return r.json(), None

    # parse creds, write warning
    if isinstance(creds, Mapping):
        user, pw = creds['username'], creds['password']
    else:
        user, pw = creds
    if plaintextcreds:
        logger.warning('You provided credentials in plain text. DO NOT save '
                       'these in a repository or otherwise post them online')
        deprecation_warning(
            'Please use `pyam.iiasa.set_config(<user>, <pwd>)`'
            ' to store your credentials in a file!',
            'Providing credentials in plain text')

    # get user token
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    data = {'username': user, 'password': pw}
    url = '/'.join([base_url, 'login'])
    r = requests.post(url, headers=headers, data=json.dumps(data))
    _check_response(r, 'Login failed for user: {}'.format(user))
    return r.json(), user
Example #3
0
def convert_gwp(context, qty, to):
    """Helper for :meth:`convert_unit` to perform GWP conversions."""
    # Remove a leading 'gwp_' to produce the metric name
    if context is not None and context.startswith("gwp_"):
        context = context[len("gwp_"):]
        deprecation_warning(
            f"Use context='{context}' instead",
            type='Prefixing a context with "gwp_"',
            stacklevel=5,
        )
    metric = context

    # Extract the species from *qty* and *to*, allowing supported aliases
    species_from, units_from = extract_species(qty[1])
    species_to, units_to = extract_species(to)

    try:
        # Convert using a (magnitude, unit) tuple with only units, and explicit
        # input and output units
        result = iam_units.convert_gwp(metric, (qty[0], units_from),
                                       species_from, species_to)
    except (AttributeError, ValueError):
        # Missing *metric*, or *species_to* contains invalid units. pyam
        # promises UndefinedUnitError in these cases. Use a subclass (above) to
        # add a usage hint.
        raise UndefinedUnitError(species_to) from None
    except pint.DimensionalityError:
        # Provide an exception with the user's inputs
        raise pint.DimensionalityError(qty[1], to) from None

    # Other exceptions are not caught and will pass up through convert_unit()

    if units_to:
        # Also convert the units
        result = result.to(units_to)
    else:
        # *to* was only a species name. Provide units based on input and the
        # output species name.
        to = iam_units.format_mass(result, species_to, spec=":~")

    return result, to
Example #4
0
 def metadata(self, default=True):
     """Deprecated, use :meth:`Connection.meta`"""
     # TODO: deprecate/remove this function in release >=0.8
     deprecation_warning('Use `Connection.meta()` instead.')
     return self.meta(default=default)
Example #5
0
 def available_metadata(self):
     """Deprecated, use :attr:`Connection.meta_columns`"""
     # TODO: deprecate/remove this function in release >=0.8
     deprecation_warning('Use `Connection.meta_columns` instead.')
     return self.meta_columns
Example #6
0
 def scenario_list(self, default=True):
     """Deprecated, use :meth:`Connection.index`"""
     deprecation_warning('Use `Connection.index()` instead.')
     return self._query_index(default)