2015-06-02 17 views
1

我已經看到Bluemix燒瓶示例項目:https://github.com/IBM-Bluemix/bluemix-python-flask-sample如何從Bluemix中運行的Flask應用程序連接到Cloudant?

如何從此燒瓶應用程序連接到Cloudant?

注:

  • 我知道如何使用燒瓶中。
  • 我已經看到了使用requests庫連接到Cloudant的說明,這就是我想要使用的方法。
  • 我見過Cloudant API documentation,我對不同的API方法感到滿意。我跟着
+0

downvoters:請說出你投票的原因,以便改善問題。沒有評論=不知道什麼是錯的。 –

回答

5

的步驟,使flask sample project工作:

  1. 按照示例項目README的指示和部署你的代碼Bluemix
  2. 登錄到Bluemix控制檯並添加Cloudant服務您的應用程序
  3. 修改welcome.pyrequirements.txt源代碼以連接到Cloudant。 (請參閱下面的示例)
  4. 使用cf push將更改推送到Cloudant。
  5. 擊中URL http://yourbluemixurl/createdb/test創建一個名爲 '測試'

示例代碼數據庫:

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 
相關問題