如何从Bluemix中运行的Flask应用程序连接到Cloudant?

时间:2015-06-02 13:35:12

标签: python flask ibm-cloud cloudant

我见过Bluemix的烧瓶示例项目:https://github.com/IBM-Bluemix/bluemix-python-flask-sample

如何从此烧瓶应用程序连接到Cloudant?

注意:

  • 我知道如何使用烧瓶。
  • 我已经看到了使用requests库连接到Cloudant的说明,这是我想要使用的方法。
  • 我见过Cloudant API documentation,我对不同的API方法感到满意。

1 个答案:

答案 0 :(得分:5)

我为使flask sample project工作所采取的步骤:

  1. 按照示例项目README中的说明进行操作,并将代码部署到Bluemix
  2. 登录Bluemix控制台并向您的应用程序添加Cloudant服务
  3. 修改welcome.pyrequirements.txt源代码以连接到Cloudant。 (见下面的例子)
  4. 使用cf push将您的更改推送到Cloudant。
  5. 点击网址http://yourbluemixurl/createdb/test以创建名为' test'
  6. 的数据库

    示例代码:

    <强> 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