我看过 Bluemix 的 flask 示例项目:https://github.com/IBM-Bluemix/bluemix-python-flask-sample
如何从这个 Flask 应用程序连接到 Cloudant?
注意:
- 我知道如何使用 flask 。
- 我已经看到使用 requests 连接到 Cloudant 的说明图书馆,这就是我想使用的方法。
- 我见过 Cloudant API documentation我对不同的 API 方法很满意。
请您参考如下方法:
我制作 flask sample project 所遵循的步骤工作:
- 按照示例项目自述文件中的说明将您的代码部署到 Bluemix
- 登录到 Bluemix 控制台并将 Cloudant 服务添加到您的应用程序
- 修改
welcome.py和requirements.txt源代码以连接到 Cloudant。 (见下面的例子) - 使用
cf push将您的更改推送到 Cloudant。 - 点击 url
http://yourbluemixurl/createdb/test创建一个名为“test”的数据库
示例代码:
欢迎.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
