An In-depth Guide to IBM Cloud Object Storage: Part 2: Use COS in python application

rafflesia Khan
3 min readOct 26, 2023

--

In Part 1, we have learned how to set up IBM Cloud Object Storage (COS) instance with a bucket and the necessary configurations. In this blog, we will create a flask app that can display images from COS and upload them to it.

To create a simple Flask project that allows users to upload images to IBM Cloud Storage and display a gallery, follow these steps:

Prerequisites:

1. Install necessary Python packages:

pip install Flask ibm-cos-sdk

2. Create an IBM Cloud account and set up an instance of Object Storage. Then, obtain your API key, service instance ID, endpoint URL, and bucket name. Please check Part 1 for setting up a COS instance with a bucket and necessary configuration.

Create the Flask App:

1. Create a new directory named `flask_ibm_app`, then navigate into it:

mkdir flask_ibm_app
cd flask_ibm_app
mkdir uploads
mkdir templates

2. Create a new file named `app.py` and add the following code:

from flask import Flask, render_template, redirect, url_for, request, send_from_directory
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from wtforms.validators import DataRequired
import os
import ibm_boto3
from werkzeug.utils import secure_filename
from ibm_botocore.client import Config

app = Flask(__name__)
app.config['SECRET_KEY'] = 'YOUR_SECRET_KEY'
app.config['UPLOAD_FOLDER'] = './uploads' # local directory for temporary storage
app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])

# IBM Cloud Object Storage Configuration
IBM_COS_ENDPOINT = 'YOUR_IBM_COS_ENDPOINT' # e.g. 'https://s3.us-south.cloud-object-storage.appdomain.cloud'
IBM_COS_API_KEY = 'YOUR_IBM_COS_API_KEY'
IBM_COS_AUTH_ENDPOINT = 'https://iam.cloud.ibm.com/identity/token'
IBM_COS_SERVICE_INSTANCE_ID = 'YOUR_IBM_COS_SERVICE_INSTANCE_ID'
IBM_COS_BUCKET_NAME = 'YOUR_IBM_COS_BUCKET_NAME'

cos = ibm_boto3.client("s3",
ibm_api_key_id=IBM_COS_API_KEY,
ibm_service_instance_id=IBM_COS_SERVICE_INSTANCE_ID,
ibm_auth_endpoint=IBM_COS_AUTH_ENDPOINT,
config=Config(signature_version="oauth"),
endpoint_url=IBM_COS_ENDPOINT
)

class UploadForm(FlaskForm):
file = FileField(validators=[DataRequired()])
submit = SubmitField('Upload')

@app.route('/', methods=['GET', 'POST'])
def index():
form = UploadForm()
if form.validate_on_submit():
file = form.file.data
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Upload to IBM COS
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb') as file_data:
cos.upload_fileobj(Fileobj=file_data, Bucket=IBM_COS_BUCKET_NAME, Key=filename)
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('index'))
# Get list of all images from IBM COS
image_files = cos.list_objects(Bucket=IBM_COS_BUCKET_NAME)['Contents']
return render_template('index.html', form=form, image_files=image_files)

@app.route('/image/<filename>', methods=['GET'])
def serve_image(filename):
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
cos.download_file(Bucket=IBM_COS_BUCKET_NAME, Key=filename, Filename=file_path)
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

if __name__ == '__main__':
app.run(debug=True)

Replace the placeholders (`YOUR_IBM_COS_ENDPOINT`, `YOUR_IBM_COS_API_KEY`, etc.) with your own IBM Cloud Object Storage details.

3. Create a templates folder and add a file named `index.html`:

<!DOCTYPE html>
<html>
<head>
<title>Image Gallery</title>
</head>
<body>
<h1>Image Gallery</h1>
<form action="/" method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.file.label }} {{ form.file() }}<br>
{{ form.submit() }}
</form>
<hr>
<h2>Images</h2>
<ul>
{% for image in image_files %}
<li><img src="{{ url_for('serve_image', filename=image['Key']) }}" width="200"></li>
{% endfor %}
</ul>
</body>
</html>

4. Run the app:

python app.py

Navigate to `http://127.0.0.1:5000/` to see the image gallery and upload functionality.

Here is a demo of the application

flask_ibm_app demo

This is our COS bucket after uploading images from the app

COS bucket with uploaded images from the app

Note: Always review and improve the code before deploying to a production environment, as this code might include secret information about your cloud instance. Also, try using a config file instead of adding all secret keys as plain text.

The full application code can be found in my Github repo [flask_ibm_app]

Conclusion

With Part 1 and Part 2 completion, you are now an IBM COS user. Happy coding!

--

--