Skip to content

logging, service_url and auth_type case insensitive changes #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,35 @@ authenticator = NoAuthAuthenticator()
If you encounter an issue with this project, you are welcome to submit a [bug report](https://github.com/IBM/python-sdk-core/issues).
Before opening a new issue, please search for similar issues. It's possible that someone has already reported it.

## Logging

### Enable logging

```python
import logging
logging.basicConfig(level=logging.DEBUG)
```

This would show output of the form:
```
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): iam.cloud.ibm.com:443
DEBUG:urllib3.connectionpool:https://iam.cloud.ibm.com:443 "POST /identity/token HTTP/1.1" 200 1809
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "POST /assistant/api/v1/workspaces?version=2018-07-10 HTTP/1.1" 201 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "GET /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10&export=true HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443
DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "DELETE /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10 HTTP/1.1" 200 28
```

### Low level request and response dump
To get low level information of the requests/ responses:

```python
from http.client import HTTPConnection
HTTPConnection.debuglevel = 1
```

## Open source @ IBM

Find more open source projects on the [IBM Github Page](http://github.com/IBM)
Expand Down
21 changes: 12 additions & 9 deletions ibm_cloud_sdk_core/base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class BaseService(object):
SDK_NAME = 'ibm-python-sdk-core'

def __init__(self,
url,
service_url,
authenticator=None,
disable_ssl_verification=False,
display_name=None):
Expand All @@ -47,7 +47,7 @@ def __init__(self,
:attr bool disable_ssl_verification: enables/ disables ssl verification
:attr str display_name the name used for mapping services in environment file
"""
self.url = url
self.service_url = service_url
self.http_config = {}
self.jar = CookieJar()
self.authenticator = authenticator
Expand Down Expand Up @@ -100,16 +100,16 @@ def set_disable_ssl_verification(self, status=False):
"""
self.disable_ssl_verification = status

def set_url(self, url):
def set_service_url(self, service_url):
"""
Sets the url
Sets the service url
"""
if has_bad_first_or_last_char(url):
if has_bad_first_or_last_char(service_url):
raise ValueError(
'The url shouldn\'t start or end with curly brackets or quotes. '
'Be sure to remove any {} and \" characters surrounding your url'
'The service url shouldn\'t start or end with curly brackets or quotes. '
'Be sure to remove any {} and \" characters surrounding your service url'
)
self.url = url
self.service_url = service_url

def get_authenticator(self):
"""
Expand Down Expand Up @@ -164,7 +164,10 @@ def prepare_request(self, method, url, headers=None,
params=None, data=None, files=None, **kwargs):
request = {'method': method}

request['url'] = self.url + url
# validate the service url is set
if not self.service_url:
raise ValueError('The service_url is required')
request['url'] = self.service_url + url

headers = remove_null_values(headers) if headers else {}
headers = cleanup_values(headers)
Expand Down
6 changes: 3 additions & 3 deletions ibm_cloud_sdk_core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,15 @@ def read_from_vcap_services(service_name):
return vcap_service_credentials

def contruct_authenticator(config):
auth_type = config.get('auth_type') if config.get('auth_type') else 'iam'
auth_type = config.get('auth_type').lower() if config.get('auth_type') else 'iam'
authenticator = None
from .authenticators import BasicAuthenticator, BearerTokenAuthenticator, CloudPakForDataAuthenticator, IAMAuthenticator, NoAuthAuthenticator

if auth_type == 'basic':
authenticator = BasicAuthenticator(
username=config.get('username'),
password=config.get('password'))
elif auth_type == 'bearerToken':
elif auth_type == 'bearertoken':
authenticator = BearerTokenAuthenticator(
bearer_token=config.get('bearer_token'))
elif auth_type == 'cp4d':
Expand All @@ -175,7 +175,7 @@ def contruct_authenticator(config):
client_id=config.get('client_id'),
client_secret=config.get('client_secret'),
disable_ssl_verification=config.get('auth_disable_ssl'))
elif auth_type == 'noAuth':
elif auth_type == 'noauth':
authenticator = NoAuthAuthenticator()

return authenticator
20 changes: 13 additions & 7 deletions test/test_base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ class AnyServiceV1(BaseService):

def __init__(self,
version,
url=default_url,
service_url=default_url,
authenticator=None,
disable_ssl_verification=False):
BaseService.__init__(
self,
url=url,
service_url=service_url,
authenticator=authenticator,
disable_ssl_verification=disable_ssl_verification,
display_name='Watson')
Expand Down Expand Up @@ -162,7 +162,7 @@ def test_iam():
status=200)
responses.add(
responses.GET,
'https://gateway-s.watsonplatform.net/watson/api',
url='https://gateway.watsonplatform.net/test/api',
body=json.dumps({
"foobar": "baz"
}),
Expand Down Expand Up @@ -358,13 +358,13 @@ def test_default_headers():
with pytest.raises(TypeError):
service.set_default_headers('xxx')

def test_set_url():
def test_set_service_url():
service = AnyServiceV1('2018-11-20', authenticator=NoAuthAuthenticator())
with pytest.raises(ValueError) as err:
service.set_url('{url}')
assert str(err.value) == 'The url shouldn\'t start or end with curly brackets or quotes. Be sure to remove any {} and \" characters surrounding your url'
service.set_service_url('{url}')
assert str(err.value) == 'The service url shouldn\'t start or end with curly brackets or quotes. Be sure to remove any {} and \" characters surrounding your service url'

service.set_url('my_url')
service.set_service_url('my_url')

def test_get_authenticator():
auth = BasicAuthenticator('my_username', 'my_password')
Expand Down Expand Up @@ -420,3 +420,9 @@ def test_json():
service = AnyServiceV1('2018-11-20', authenticator=NoAuthAuthenticator())
req = service.prepare_request('POST', url='', headers={'X-opt-out': True}, data={'hello': 'world'})
assert req.get('data') == "{\"hello\": \"world\"}"

def test_service_url_not_set():
service = BaseService(service_url='', authenticator=NoAuthAuthenticator(), display_name='Watson')
with pytest.raises(ValueError) as err:
service.prepare_request('POST', url='')
assert str(err.value) == 'The service_url is required'