Chris Snow
Chris Snow

Reputation: 24588

How can I connect to Cloudant from a Flask App running in Bluemix?

I have seen a flask sample project for Bluemix: https://github.com/IBM-Bluemix/bluemix-python-flask-sample

How can I connect to Cloudant from this flask application?

Note:

Upvotes: 1

Views: 1781

Answers (1)

Chris Snow
Chris Snow

Reputation: 24588

The steps I followed to make the flask sample project work:

  1. Follow the instructions in the sample project README and deploy your code to Bluemix
  2. Login to the Bluemix console and add a Cloudant service to your application
  3. Modify the welcome.py and requirements.txt source code to connect to Cloudant. (see example below)
  4. Use cf push to push your changes to Cloudant.
  5. Hit the url http://yourbluemixurl/createdb/test to create a database named 'test'

Example code:

welcome.py

import os
import json
import requests
from flask import Flask

app = Flask(__name__)

app.config.update(
    DEBUG=True,
)

@app.route('/')
def welcome():
    return 'Welcome to flask and Cloudant on Bluemix.'

@app.route('/createdb/<db>')
def create_db(db):
    try:
        vcap = json.loads(os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB']

        cl_username = vcap[0]['credentials']['username']
        cl_password = vcap[0]['credentials']['password']

        url         = vcap[0]['credentials']['url']
        auth        = ( cl_username, cl_password )

    except:
        return 'A Cloudant service is not bound to the application.  Please bind a Cloudant service and try again.'

    requests.put( url + '/' + db, auth=auth )
    return 'Database %s created.' % db

port = os.getenv('VCAP_APP_PORT', '5000')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=int(port))

requirements.txt

Flask==0.10.1
requests==2.7.0

Upvotes: 5

Related Questions