[PYTHON] Get data from Cloudant with Bluemix flask

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

cloudant_jun2700.png

Execution result http://ekzemplarocc.mybluemix.net/getdb/test

cloudant_jun2701.png

http://ekzemplarocc.mybluemix.net/getdb2/test

cloudant_jun2702.png

The app must be connected to Cloudant NoSQL to run.

Recommended Posts

Get data from Cloudant with Bluemix flask
[Note] Get data from PostgreSQL with Python
Get data from an oscilloscope with pyVISA
Get structural data from CHEMBLID
Get Youtube data with python
Get data from database via ODBC with Python (Access)
Get data from analytics API with Google API Client for python
Get data from Quandl in Python
Get one column from DataFrame with DataFrame
[Python] Get economic data with DataReader
Get data from Twitter using Tweepy
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Get additional data in LDAP with python
Receive textual data from mysql with python
Get html from element with Python selenium
Get time series data from k-db.com in Python
Get stock price data with Quandl API [Python]
I tried to get CloudWatch data with Python
Get 10 or more data from SSM parameter store
Get data files from elsewhere during pip install
Extract data from a web page with Python
Get Amazon RDS (PostgreSQL) data using SQL with pandas
How to scrape image data from flickr with python
Get financial data with python (then a little tinkering)
Get schedule from Garoon SOAP API with Python + Zeep
Get data from GPS module at 10Hz in Python
How to get more than 1000 data with SQLAlchemy + MySQLdb
A server that echoes data POSTed with flask / python
Get comments and subscribers with the YouTube Data API
Get mail from Gmail and label it with Python3
I tried collecting data from a website with Scrapy
[Basics of data science] Collecting data from RSS with python
* Android * [HTTP communication_2] HTTP communication with Flask (hit WebAPI [GET, POST])
Data analysis with python 2
Introducing WebPay from Flask
Extract data from S3
Visualize data with Streamlit
Flask Tutorial # 1 ~ GET Request ~
Data visualization with pandas
IP restrictions with Flask
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
Get started with MicroPython
Data manipulation with Pandas!
Get Tweets with Tweepy
Get Gzip-compressed data on-memory
Shuffle data with pandas
Get date with python
Data Augmentation with openCV
Get started with Mezzanine
Normarize data with Scipy
Hello world with flask
Data analysis with Python
Programming with Python Flask
LOAD DATA with PyMysql
A memo that reads data from dashDB with Python & Spark
Getting Started with Drawing with matplotlib: Creating Diagrams from Data Files
[Linux] Copy data from Linux to Windows with a shell script
Notes on importing data from MySQL or CSV with Python
Check! Get sensor data via Bluetooth with Raspberry Pi ~ Preparation
Get the package version to register with PyPI from Git
Get rid of dirty data with Python and regular expressions