Skip to content

Commit

Permalink
added cred file support
Browse files Browse the repository at this point in the history
  • Loading branch information
gidden committed Jul 16, 2019
1 parent 7ba81ba commit bea472e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
22 changes: 18 additions & 4 deletions pyam/iiasa.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import collections
import json
import logging
import os
import requests
import warnings
import yaml

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -34,16 +36,25 @@ def _get_token(creds):
return requests.get(url).json()

# otherwise read creds and try to login
filecreds = False
try:
if isinstance(creds, collections.Mapping):
user, pw = creds['username'], creds['password']
elif os.path.exists(str(creds)):
with open(str(creds), 'r') as stream:
creds = yaml.safe_load(stream)
user, pw = creds['username'], creds['password']
filecreds = True
else:
user, pw = creds
except Exception as e:
msg = 'Could not read credentials: {}\n{}'.format(
creds, str(e))
raise type(e)(msg)

if not filecreds:
warnings.warn('You provided credentials in plain text. DO NOT save ' +
'these in a repository or otherwise post them online')

headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
data = {'username': user, 'password': pw}
Expand All @@ -65,9 +76,12 @@ def __init__(self, name=None, creds=None):
name : str, optional
A valid database name. For available options, see
valid_connection_names().
creds : list-like or dict, optional
An ordered container with entries of 'username' and 'password',
or a dictionary with the same keys.
creds : str, list-like, or dict, optional
Either:
- a yaml filename/path with entries of 'username' and 'password'
(preferred)
- an ordered container (tuple, list, etc.) with the same values
- a dictionary with the same keys
"""
self._token = _get_token(creds)

Expand Down
11 changes: 11 additions & 0 deletions tests/test_iiasa.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import copy
import pytest
import os
import yaml

import numpy.testing as npt

Expand All @@ -25,6 +26,16 @@ def test_anon_conn_warning():
assert conn.current_connection == 'IXSE_SR15'


@pytest.mark.skipif(not CONN_ENV_AVAILABLE, reason=CONN_ENV_REASON)
def test_conn_creds_file(tmp_path):
user, pw = os.environ[TEST_ENV_USER], os.environ[TEST_ENV_PW]
path = tmp_path / 'config.yaml'
with open(path, 'w') as f:
yaml.dump({'username': user, 'password': pw}, f)
conn = iiasa.Connection('IXSE_SR15', creds=path)
assert conn.current_connection == 'IXSE_SR15'


@pytest.mark.skipif(not CONN_ENV_AVAILABLE, reason=CONN_ENV_REASON)
def test_conn_creds_tuple():
user, pw = os.environ[TEST_ENV_USER], os.environ[TEST_ENV_PW]
Expand Down

0 comments on commit bea472e

Please sign in to comment.