The next page describes how to connect to Cloudant. How can I connect to Cloudant from a Flask App running in Bluemix?
In this example, there is only an example of creating a database, so I created a sample of the database read.
The data was manually loaded into the created database.
Only welcome.py needs to be modified.
# -*- coding: utf-8 -*-
#
# welcome.py
# ----------------------------------------------------------------------
import os
import json
import requests
from flask import Flask
from flask import jsonify
app = Flask(__name__)
app.config.update(
DEBUG=True,
)
# ----------------------------------------------------------------------
def define_url_auth_proc():
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 )
#
return url,auth
# ----------------------------------------------------------------------
@app.route('/')
def welcome():
return app.send_static_file('index.html')
# ----------------------------------------------------------------------
@app.route('/getdb/<db>')
def get_db(db):
try:
url,auth = define_url_auth_proc()
except:
return 'A Cloudant service is not bound to the application. Please bind a Cloudant service and try again.'
rr=requests.get( url + '/' + db, auth=auth )
dict=rr.json()
return jsonify(results=dict)
# ----------------------------------------------------------------------
@app.route('/getdb2/<db>')
def get_db2(db):
try:
url,auth = define_url_auth_proc()
except:
return 'A Cloudant service is not bound to the application. Please bind a Cloudant service and try again.'
url_aa = url + '/' + db + '/_all_docs?include_docs=true'
rr=requests.get( url_aa, auth=auth )
dict=rr.json()
return jsonify(results=dict)
#
# ----------------------------------------------------------------------
@app.route('/createdb/<db>')
def create_db(db):
try:
url,auth = define_url_auth_proc()
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))
# ----------------------------------------------------------------------
Status of manually entering data
Execution result http://ekzemplarocc.mybluemix.net/getdb/test
http://ekzemplarocc.mybluemix.net/getdb2/test
The app must be connected to Cloudant NoSQL to run.
Recommended Posts