Skip to content

Commit

Permalink
chore(user-agent): User agent methods and date time parsing in utils
Browse files Browse the repository at this point in the history
  • Loading branch information
ehdsouza committed Mar 15, 2019
1 parent 65e17d0 commit 416dd82
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 36 deletions.
1 change: 1 addition & 0 deletions ibm_cloud_sdk_core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@
from .detailed_response import DetailedResponse
from .iam_token_manager import IAMTokenManager
from .api_exception import ApiException
from .utils import datetime_to_string, string_to_datetime
44 changes: 13 additions & 31 deletions ibm_cloud_sdk_core/base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import dateutil.parser as date_parser
import os
from os.path import dirname, isfile, join, expanduser, abspath
import platform
Expand Down Expand Up @@ -53,6 +52,7 @@ class BaseService(object):
IAM_URL = 'iam_url'
APIKEY_DEPRECATION_MESSAGE = 'Authenticating with apikey is deprecated. Move to using Identity and Access Management (IAM) authentication.'
DEFAULT_CREDENTIALS_FILE_NAME = 'ibm-credentials.env'
SDK_NAME = 'ibm-python-sdk-core'

def __init__(self, vcap_services_name, url, username=None, password=None,
use_vcap_services=True, api_key=None,
Expand Down Expand Up @@ -81,8 +81,7 @@ def __init__(self, vcap_services_name, url, username=None, password=None,
raise ValueError('The URL shouldn\'t start or end with curly brackets or quotes. '
'Be sure to remove any {} and \" characters surrounding your URL')

user_agent_string = 'ibm-python-sdk-core-' + __version__ + self.get_os_info()
self.user_agent_header = self.set_user_agent_header(user_agent_string)
self.set_user_agent_header(self.build_user_agent())

# 1. Credentials are passed in constructor
if api_key is not None:
Expand Down Expand Up @@ -137,7 +136,7 @@ def _load_from_credential_file(self, service_name, separator='='):
:param str separator: the separator for key value pair
"""
# File path specified by an env variable
credential_file_path = os.getenv("IBM_CREDENTIALS_FILE")
credential_file_path = os.getenv('IBM_CREDENTIALS_FILE')

# Home directory
if credential_file_path is None:
Expand Down Expand Up @@ -174,11 +173,11 @@ def _set_credential_based_on_type(self, service_name, key, value):
self.set_iam_url(value)

def _load_from_vcap_services(self, service_name):
vcap_services = os.getenv("VCAP_SERVICES")
vcap_services = os.getenv('VCAP_SERVICES')
if vcap_services is not None:
services = json_import.loads(vcap_services)
if service_name in services:
return services[service_name][0]["credentials"]
return services[service_name][0]['credentials']
else:
return None

Expand Down Expand Up @@ -251,18 +250,19 @@ def set_default_headers(self, headers):
else:
raise TypeError("headers parameter must be a dictionary")

def get_os_info(self):
user_agent_string = ''
user_agent_string += ' ' + platform.system() # OS
user_agent_string += ' ' + platform.release() # OS version
user_agent_string += ' ' + platform.python_version() # Python version
return user_agent_string
def get_system_info(self):
return '{0} {1} {2}'.format(platform.system(), # OS
platform.release(), # OS version
platform.python_version()) # Python version

def build_user_agent(self):
return '{0}-{1} {2}'.format(self.SDK_NAME, __version__, self.get_system_info())

def get_user_agent_header(self):
return self.user_agent_header

def set_user_agent_header(self, user_agent_string=None):
self.user_agent_header = {'user-agent': user_agent_string}
self.user_agent_header = {'User-Agent': user_agent_string}

def set_http_config(self, http_config):
"""
Expand Down Expand Up @@ -360,21 +360,3 @@ def _convert_list(val):
@staticmethod
def _encode_path_vars(*args):
return (requests.utils.quote(x, safe='') for x in args)

@staticmethod
def _datetime_to_string(datetime):
"""
Serializes a datetime to a string.
:param datetime: datetime value
:return: string. containing iso8601 format date string
"""
return datetime.isoformat().replace('+00:00', 'Z')

@staticmethod
def _string_to_datetime(string):
"""
Deserializes string to datetime.
:param string: string containing datetime in iso8601 format
:return: datetime.
"""
return date_parser.parse(string)
18 changes: 18 additions & 0 deletions ibm_cloud_sdk_core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import dateutil.parser as date_parser

def has_bad_first_or_last_char(str):
return str is not None and (str.startswith('{') or str.startswith('"') or str.endswith('}') or str.endswith('"'))

Expand All @@ -32,3 +34,19 @@ def cleanup_value(value):
if isinstance(value, bool):
return 'true' if value else 'false'
return value

def datetime_to_string(datetime):
"""
Serializes a datetime to a string.
:param datetime: datetime value
:return: string. containing iso8601 format date string
"""
return datetime.isoformat().replace('+00:00', 'Z')

def string_to_datetime(string):
"""
Deserializes string to datetime.
:param string: string containing datetime in iso8601 format
:return: datetime.
"""
return date_parser.parse(string)
11 changes: 6 additions & 5 deletions test/test_base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,14 +349,15 @@ def _from_dict(cls, _dict):
res_str = service._convert_list(temp)
assert res_str == 'default,123'

date = service._string_to_datetime('2017-03-06 16:00:04.159338')
assert date.day == 6
res = service._datetime_to_string(date)
assert res == '2017-03-06T16:00:04.159338'

def test_default_headers():
service = AnyServiceV1('2018-11-20', username='username', password='password')
service.set_default_headers({'xxx': 'yyy'})
assert service.default_headers == {'xxx': 'yyy'}
with pytest.raises(TypeError):
service.set_default_headers('xxx')

def test_user_agent_header():
service = AnyServiceV1('2018-11-20', username='username', password='password')
user_agent_header = service.get_user_agent_header()
assert user_agent_header is not None
assert user_agent_header['User-Agent'] is not None
7 changes: 7 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from ibm_cloud_sdk_core import string_to_datetime, datetime_to_string

def test_datetime_conversion():
date = string_to_datetime('2017-03-06 16:00:04.159338')
assert date.day == 6
res = datetime_to_string(date)
assert res == '2017-03-06T16:00:04.159338'

0 comments on commit 416dd82

Please sign in to comment.