Working With IBM Cloud Object Storage In Python¶

  1. IBM Cloud Object Storage
  2. Import Credentials
  3. File Uploads
  4. File Downloads
  5. New Credentials

Introduction¶

If you create project in Data Science Experience , you get two options for stoarage .

  1. Object Storage (Swift API)
  2. IBM Cloud Object Storage

IBM Cloud Object Storage(COS) provides flexible storage solution to the user and it can be accessed over HTTP using a REST API. In this notebook, we will learn how to access IBM Cloud Object Storage in python.

Import Credentials¶

In [122]:
credentials = {
    'IBM_API_KEY_ID': '*******************************',
    'IAM_SERVICE_ID': '*******************************',
    'ENDPOINT': '*******************************',
    'IBM_AUTH_ENDPOINT': '*******************************',
    'BUCKET': '*******************************',
    'FILE': 'wine.csv'
}
In [2]:
# The code was removed by Watson Studio for sharing.
In [9]:
from ibm_botocore.client import Config
import ibm_boto3

cos = ibm_boto3.client(service_name='s3',
    ibm_api_key_id=credentials['IBM_API_KEY_ID'],
    ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
    ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
    config=Config(signature_version='oauth'),
    endpoint_url=credentials['ENDPOINT'])

File Uploads¶

In [136]:
# Upload file wine.csv from wine folder into project bucket as wine_data.csv
cos.upload_file(Filename='wine/wine.csv',Bucket=credentials['BUCKET'],Key='wine_data.csv')
# upload zip file
cos.upload_file('wine.gz', credentials['BUCKET'],'wine.gz')
# Upload pickle object
cos.upload_file('GB_Classification_model.pkl', credentials['BUCKET'],'GB_Classification_model.pkl')
In [27]:
# upload file like object 
with open('wine.csv', 'rb') as data:
    cos.upload_fileobj(data,  credentials['BUCKET'], 'wine_bytes')
In [1]:
from ibm_botocore.client import Config
import ibm_boto3

def upload_file_cos(credentials,local_file_name,key):  
    cos = ibm_boto3.client(service_name='s3',
    ibm_api_key_id=credentials['IBM_API_KEY_ID'],
    ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
    ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
    config=Config(signature_version='oauth'),
    endpoint_url=credentials['ENDPOINT'])
    try:
        res=cos.upload_file(Filename=local_file_name, Bucket=credentials['BUCKET'],Key=key)
    except Exception as e:
        print(Exception, e)
    else:
        print(' File Uploaded')
    
In [140]:
upload_file_cos(credentials,'GB_Classification_model.pkl','GB_Classification_model1.pkl')
 File Uploaded

File Downloads¶

In [152]:
cos.download_file(Bucket=credentials['BUCKET'],Key='wine.csv',Filename='data/wine1.csv')
In [31]:
# download file like object 
with open('wine_copy.csv', 'wb') as data:
    cos.download_fileobj(credentials['BUCKET'], 'wine_bytes', data)
In [2]:
from ibm_botocore.client import Config
import ibm_boto3

def download_file_cos(credentials,local_file_name,key):  
    cos = ibm_boto3.client(service_name='s3',
    ibm_api_key_id=credentials['IBM_API_KEY_ID'],
    ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
    ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
    config=Config(signature_version='oauth'),
    endpoint_url=credentials['ENDPOINT'])
    try:
        res=cos.download_file(Bucket=credentials['BUCKET'],Key=key,Filename=local_file_name)
    except Exception as e:
        print(Exception, e)
    else:
        print('File Downloaded')
In [15]:
download_file_cos(credentials,'model/GB_model.pkl','GB_Classification_model.pkl')
 File Downloaded

New Credentials¶

In [10]:
cos_credentials={
  "apikey": "***********************",
  "endpoints": "***********************",
  "iam_apikey_description": "***********************",
  "iam_apikey_name": "***********************",
  "iam_role_crn": "***********************",
  "iam_serviceid_crn": "***********************",
  "resource_instance_id": "***********************"
}

auth_endpoint = 'https://iam.bluemix.net/oidc/token'
service_endpoint = 'https://s3-api.us-geo.objectstorage.softlayer.net'

cos = ibm_boto3.client('s3',
                         ibm_api_key_id=cos_credentials['apikey'],
                         ibm_service_instance_id=cos_credentials['resource_instance_id'],
                         ibm_auth_endpoint=auth_endpoint,
                         config=Config(signature_version='oauth'),
                         endpoint_url=service_endpoint)
In [18]:
# The code was removed by Watson Studio for sharing.

List Buckets¶

In [9]:
for bucket in cos.list_buckets()['Buckets']:
    print(bucket['Name'])
bluemixaccounts-hyx4v4raz-catalog-0422c6e2
buckettest
communitycosdf0fcb47bb7d48a1a847cee6cbe1bc57
cos-test-bucket1
cos-test-bucket2
cos1ab43f6f665aa4daaa9066513b83bdd32
cosproject062645eac3ca4746837c8897df3b7a0e
coswithoutenv2e0e51cec9bf472abaaf00aeebfdef7d
datacatalogandrefinetestc74f307cb1a74fec995e80d930357bac
demo9840d8da1d6049a8aa1da5e6906c41ee
dsx-sy8mm45a-catalog-0422c6e2
dsxenterpriseupsell0a087e0d42b24ba39ed1005696eec475
havi-r1hrlcyf-catalog-0422c6e2
havi914f33ced68240729566241410612716
music-bygusmcaz-catalog-0422c6e2

Create/Delete Buckets¶

In [6]:
cos.create_bucket(Bucket='bucket1-test')
Out[6]:
{'ResponseMetadata': {'HTTPHeaders': {'content-length': '0',
   'date': 'Tue, 30 Jan 2018 21:11:08 GMT',
   'server': 'Cleversafe/3.12.1.28',
   'x-amz-request-id': '6a8e444f-4ffa-4e0e-9f98-946df69ef346',
   'x-clv-request-id': '6a8e444f-4ffa-4e0e-9f98-946df69ef346',
   'x-clv-s3-version': '2.5'},
  'HTTPStatusCode': 200,
  'HostId': '',
  'RequestId': '6a8e444f-4ffa-4e0e-9f98-946df69ef346',
  'RetryAttempts': 0}}
In [8]:
cos.delete_bucket(Bucket='bucket1-test')
Out[8]:
{'ResponseMetadata': {'HTTPHeaders': {'date': 'Tue, 30 Jan 2018 21:11:20 GMT',
   'server': 'Cleversafe/3.12.1.28',
   'x-amz-request-id': '631459c0-a70e-4492-83e3-52e2ff1e86b5',
   'x-clv-request-id': '631459c0-a70e-4492-83e3-52e2ff1e86b5',
   'x-clv-s3-version': '2.5'},
  'HTTPStatusCode': 204,
  'HostId': '',
  'RequestId': '631459c0-a70e-4492-83e3-52e2ff1e86b5',
  'RetryAttempts': 0}}
In [ ]: