def __init__(self, new_name='market-maker'): self.db_name = new_name self.client = None self.db = None # Connect to Cloudant DB and create database if not already present # if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) self.db = self.client.create_database(self.db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) self.db = self.client.create_database(self.db_name, throw_on_exists=False)
class Connection(object): def __init__(self, _user, _pwd, _account, _db): self.client = Cloudant(_user, _pwd, account=_account) self.user = _user self.host = _account self.pwd = _pwd self.db = _db def connect(self): self.client.connect() return self.client[self.db] def disconnect(self): self.client.disconnect() def register_error(self, e, author): try: err_code = uuid.uuid4() doc = { 'doc_type': 'error', 'code': str(err_code), 'message': str(e) } self.database.create_document(doc) return err_code except: return None def test_connection(self): fields = ['_id'] query = Query(self.connect(), selector={'_id': {'$gt': 0}, 'doc_type': 'test'}, fields=fields) self.disconnect() return query.result
def connect(self): self.client = Cloudant(self.DEF_USER, self.DEF_PASS, url='https://' + self.DEF_URL, connect=True) self.client.connect() db = self.client.create_database(self.db_name, throw_on_exists=False) return db
def __init__(self): mimetypes.init() cloudant_user = os.environ["CLOUDANT_USER"] cloudant_pass = os.environ["CLOUDANT_PASS"] client = Cloudant(cloudant_user, cloudant_pass, account=cloudant_user) client.connect() session = client.session() self.database = client['scout'] self.client = client
def connect(self, name=constant.prodDb): self.dbName = name self.client = Cloudant(self.user, self.password, url='https://' + self.creds['host'], connect=True) self.db = self.client.create_database(self.dbName, throw_on_exists=False)
def config_db(): db_name = 'mydb' client, db = None, None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif "CLOUDANT_URL" in os.environ: client = Cloudant(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) return client, db
def sync_db(): """ 同步数据库 """ client = Cloudant(app.config.COUCHDB_USER, app.config.COUCHDB_PASSWORD, url=app.config.COUCHDB_URL, connect=True) db = client.create_database(app.config.COUCHDB_DATABASE) db.create_query_index(index_name='version_index', fields=[ 'version', ]) record = client.create_database(app.config.COUCHDB_RECORDS)
def inner(*args, **kwargs): client = Cloudant(db_credentials['username'], db_credentials['password'], url=db_credentials['url']) client.connect() client.session() kwargs['client'] = client result = foo(*args, **kwargs) client.session_logout() client.disconnect() return result
def start_connection(app, loop): app.client = Cloudant(app.config.COUCHDB_USER, app.config.COUCHDB_PASSWORD, url=app.config.COUCHDB_URL, connect=True) app.db = app.client[app.config.COUCHDB_DATABASE] app.records = app.client[app.config.COUCHDB_RECORDS]
def init_app(self, app): self.client = Cloudant.iam(app.config.get("CLOUDANT_USER"), app.config.get("CLOUDANT_APIKEY"), connect=True) self.db = self.client.create_database(self.db_name, throw_on_exists=False) logging.info("Connection to Cloudant successful")
def __init__(self): super().__init__() self.charset = 'gbk' self.base_url = 'http://t66y.com' self.page_url = 'thread0806.php?fid=7&search=today' self.client = Cloudant.iam(os.environ.get('db_user'), os.environ.get('db_key'), connect=True) self.db = self.client[os.environ.get('db_name', 'serverless')] self.reply_id = 'pending_reply_list' self.day = self.utc_dt.strftime('%Y-%m-%d')
def connect_db(db_name, db_client=None): '''Connect a database client to the server configured in VCAP_SERVICES and open the named database. If the database does not exist it will be created. Returns the database client.''' db = None client = db_client if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('apps/vcap-local.json'): with open('apps/vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) else: print('No VCAP_SERVICES found') if db is not None: print('Connected to {0} database'.format(db_name)) return client
def Setup() -> database.CouchDatabase: """Creates and returns DB""" if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] # password = creds['password'] url = 'https://' + creds['host'] apiKey = creds['apikey'] # client = cloudant_iam(user, apiKey, url=url, connect=True) client = Cloudant.iam(user, apiKey, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif "CLOUDANT_URL" in os.environ: client = Cloudant.iam(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.template.json'): with open('vcap-local.template.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] # password = creds['password'] apiKey = creds['apikey'] url = 'https://' + creds['host'] # client = Cloudant(user, apiKey, url=url, connect=True) client = Cloudant.iam(user, apiKey, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) else: print("no db found") return db
def connect_db(): if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') elif "LOCAL_ENV" in app.config: vcap = app.config["LOCAL_ENV"] print('Found local VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] db_name = "test" try: client = Cloudant(user, password, url=url, connect=True) except: print("Cloudant Error") try: db = client.create_database(db_name, throw_on_exists=False) except: print("Cloudant Error") return client, db
def db_setup(app): db_name = os.getenv('DB_NAME') if db_name: print('db name is : ' + db_name) app.db_client = None app.db = None if 'CUSTOM_VCAP_SERVICES' in os.environ: c_vcap = json.loads(os.getenv('CUSTOM_VCAP_SERVICES')) creds = c_vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] app.db_client = Cloudant(user, password, url=url, connect=True) app.db = app.db_client.create_database(db_name, throw_on_exists=False) elif 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] app.db_client = Cloudant(user, password, url=url, connect=True) app.db = app.db_client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] db_name = vcap['services']['cloudantNoSQLDB'][0]['db_name'] url = 'https://' + creds['host'] app.db_client = Cloudant(user, password, url=url, connect=True) app.db = app.db_client.create_database(db_name, throw_on_exists=False)
def connect_db(): USERNAME, PASSWORD, URL, DATABASE_NAME = connect_filedb.getconfig() client = Cloudant(USERNAME, PASSWORD, url=URL) client.connect() session = client.session() if DATABASE_NAME in client.all_dbs(): return DATABASE_NAME, client else: return "No such Database exist"
class cloundant_proxy: DEF_USER = "******" DEF_PASS = "******" DEF_URL = "85503c60-2116-40ba-afba-2fac974fd814-bluemix.cloudant.com" def __init__(self, db_name): self.db_name = db_name self.db = self.connect() def connect(self): self.client = Cloudant(self.DEF_USER, self.DEF_PASS, url='https://' + self.DEF_URL, connect=True) self.client.connect() db = self.client.create_database(self.db_name, throw_on_exists=False) return db def disconnect(self): self.client.disconnect() def __del__(self): self.disconnect()
def __init__(self): self.database = None self.acl_db = None # try to open the db, if not, create it... try: self.vcap = json.loads( os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB'] self.cl_username = self.vcap[0]['credentials']['username'] self.cl_password = self.vcap[0]['credentials']['password'] self.url = self.vcap[0]['credentials']['url'] self.auth = (self.cl_username, self.cl_password) self.client = Cloudant(self.cl_username, self.cl_password, url=self.url) self.client.connect() self.database = self.client[USER_DB] self.acl_db = self.client[ACL_DB] logger.info('Starting cloudant db at %s' % self.url) except: logger.error('Unable to load database...')
def get_db_client(cred_file): creds = None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] elif os.path.isfile(cred_file): with open(cred_file) as f: vcap = json.load(f) creds = vcap['cloudantNoSQLDB'][0]['credentials'] url = 'https://' + creds['host'] user = creds['username'] password = creds['password'] return Cloudant(user, password, url=url, connect=True)
def run(self, **kwargs): utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) bj_dt = utc_dt.astimezone(timezone( timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S') client = Cloudant.iam(os.environ.get('db_user'), os.environ.get('db_key'), connect=True) db = client['db-1'] for document in db: app_data = self.get_ms_token(**document) if document['auth_type'] == 'oauth': data = self.refresh_token(**document) document['access_token'] = data['access_token'] document['expires_time'] = int(time.time()) + 3500 document['update_time'] = bj_dt if data.get('refresh_token'): document['refresh_token'] = data['refresh_token'] app_data['expires_time'] = int(time.time()) + 3500 app_data['update_time'] = bj_dt document['app_data'] = app_data document.save() self.logger.info(f"{document['_id']} refresh done.") client.disconnect()
def init_client(self): # credentials from ENV variables - not sure if needed if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) # credentials from ENV variables for usage on IBM cloud elif "CLOUDANT_URL" in os.environ: self.client = Cloudant(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True) # credentials from local file elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) else: raise Exception("No CB credentials found") self.user_db = self.client.create_database(self.db_name, throw_on_exists=False)
app = Flask(__name__, static_url_path='') db_name = 'mydb' client = None db = None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif "CLOUDANT_URL" in os.environ: client = Cloudant(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False)
app = Flask(__name__) db_name = 'mydb' client = None db = None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) # On Bluemix, get the port number from the environment variable PORT # When running this app on the local machine, default the port to 8080 port = int(os.getenv('PORT', 8080))
class CloudantApi: db_name = 'users' client = None # client for work with cloudant db user_db = None # represents table, only one table is required for the purpose of this app def __init__(self): self.init_client() def init_client(self): # credentials from ENV variables - not sure if needed if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) # credentials from ENV variables for usage on IBM cloud elif "CLOUDANT_URL" in os.environ: self.client = Cloudant(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True) # credentials from local file elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] self.client = Cloudant(user, password, url=url, connect=True) else: raise Exception("No CB credentials found") self.user_db = self.client.create_database(self.db_name, throw_on_exists=False) def get_user(self, username): """ Retrieves specific user by username :param username: string with user's username :return: """ if username in self.user_db: return self.user_db[username] else: print('No user with username ', username, 'exists') return None def get_users(self): """ Retrieves all users :return: json list of users """ return jsonify(list(self.user_db)) def create_user(self, username, password): """ Creates a user with unique username and password :param username: unique string characterizing user :param password: password string :return: json with created user """ data = { '_id': username, 'password': password, 'seenMovies': [], 'favouriteMovies': [] } doc = self.user_db.create_document(data) data['_id'] = doc['_id'] return data def delete_user(self, username): """ Deletes a user with username """ if username in self.user_db: doc = self.user_db[username] doc.delete() return username return [] def add_seen_movie(self, username, movie): if username in self.user_db: user = self.user_db[username] user['seenMovies'].append(movie) user.save() return user['seenMovies'] else: print('No user with username ', username, 'exists') return [] def get_user_seen_movies(self, username): if username in self.user_db: return self.user_db[username]['seenMovies'] else: print('No user with username ', username, 'exists') return [] def add_favourite_movie(self, username, movie_id): """ Add a movie to the list of user's favourite movies :param username: username of the user :param movie_id: movie title :return: json list of movie titles """ if username in self.user_db: user = self.user_db[username] user['favouriteMovies'].append(movie_id) user.save() return user['favouriteMovies'] else: print('No user with username ', username, 'exists') return [] def remove_favourite_movie(self, username, movie_id): """ Removes a movie from the list of user's favourite movies :param username: username of the user :param movie_id: movie title :return: json list of movie titles """ if username in self.user_db: user = self.user_db[username] try: user['favouriteMovies'].remove(movie_id) except: print("No such movie in favourites") return [] user.save() return user['favouriteMovies'] else: print('No user with username ', username, 'exists') return [] def get_user_favourite_movies(self, username): """ Retrieves user's favourite movies :param username: username of the user :return: json list of movie titles """ if username in self.user_db: return self.user_db[username]['favouriteMovies'] else: print('No user with username ', username, 'exists') return [] def disconnect(self): if self.client: self.client.disconnect()
from cloudant import Cloudant from cloudant.result import Result import json client = Cloudant.iam("e75ee703-7ad3-46f2-91cd-f77a6a0d2094-bluemix", "vb5tLFvKQ_fpWBiSG-5lbKnU2XaMp2VeOryqTXTll7wn") client.connect() my_db = client['maindb'] sample_data = [[1, "one two three", "boiling", 100], [2, "two", "hot", 40], [3, "three", "warm", 20], [4, "four", "cold", 10], [5, "five", "freezing", 0]] documents_list = [] for document in sample_data: number = document[0] name = document[1] description = document[2] temperature = document[3] json_document = { "numberField": number, "nameField": name, "descriptionField": description, "temperatureField": temperature } documents_list.append(json_document) my_db.bulk_docs(documents_list)
from cloudant import Cloudant from docx import Document from flask import Flask, request, make_response, render_template, session, g from sklearn.preprocessing import Imputer from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.decomposition import PCA from cloudant.error import CloudantException from cloudant.result import Result, ResultByKey, QueryResult user = "******" password = "******" host = "9ef80d52-30b9-4e45-833a-75059db0825c-bluemix.cloudant.com" url = 'https://' + host client = Cloudant(user, password, url=url, connect=True) app = Flask(__name__) app.config['SECRET_KEY'] = "QWERTYUIOPASDFGHJKLZXCVBNM" @app.route('/webhook', methods=['POST']) def webhook(): url = "https://nwave-ideabot-flask-webhook-p.herokuapp.com/storedata" global output output = {} try: req = request.get_json(silent=True, force=True) sessionId = req.get("sessionId") result = req.get("result") contexts = result.get("contexts") par = contexts[2].get("parameters")
# --- IBM cloud config stuff starts cf_deployment_tracker.track() db_name = 'mydb' client = None db = None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) db = client.create_database(db_name, throw_on_exists=False) @atexit.register def shutdown(): if client:
def __init__(self, _user, _pwd, _account, _db): self.client = Cloudant(_user, _pwd, account=_account) self.user = _user self.host = _account self.pwd = _pwd self.db = _db
def __init__(self, options): self.my_database = None self.orgId = options['orgId'] self.cloudant_client = Cloudant.iam(options['username'], options['apikey'], connect=True)
def __init__(self): self.one = OneDrive() self.client = Cloudant.iam(ACCOUNT_NAME, API_KEY, connect=True) self.db = self.client.create_database(DB_NAME) self.one_type = None
from flask import Flask, render_template, jsonify from cryptography.fernet import Fernet #Object Storage Credentials auth_url = projectId = region = userId = password = #Cloudant Credentials cloud_username = cloud_password = cloud_url = client = Cloudant(cloud_username, cloud_password, url=cloud_url) client.connect() session = client.session() app = Flask(__name__) def genKey(): passWord= input('Enter key: ') salt = os.urandom(16) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32,
metrics_tracker_client.DSX('org/repo') app = Flask(__name__) client = None db = None if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) client.create_database('trainer', throw_on_exists=False) client.create_database('synapse', throw_on_exists=False) elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') creds = vcap['services']['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] client = Cloudant(user, password, url=url, connect=True) client.create_database('trainer', throw_on_exists=False) client.create_database('synapse', throw_on_exists=False) cache = dict()
class CloudantDB: def __init__(self): self.database = None self.acl_db = None # try to open the db, if not, create it... try: self.vcap = json.loads( os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB'] self.cl_username = self.vcap[0]['credentials']['username'] self.cl_password = self.vcap[0]['credentials']['password'] self.url = self.vcap[0]['credentials']['url'] self.auth = (self.cl_username, self.cl_password) self.client = Cloudant(self.cl_username, self.cl_password, url=self.url) self.client.connect() self.database = self.client[USER_DB] self.acl_db = self.client[ACL_DB] logger.info('Starting cloudant db at %s' % self.url) except: logger.error('Unable to load database...') def create_db(self): self.database = self.client.create_database(USER_DB) if self.database.exists(): return None, False return 'Unable to create %s' % USER_DB, True def get_all_documents(self): documents = [] for document in self.database: documents.append(document) if not documents: logger.error('Unable to load documents...') return None, True return {'documents': documents}, False def get_all_acl_db(self): documents = [] for document in self.acl_db: documents.append(document) if not documents: logger.error('Unable to load documents...') return None, True return {'documents': documents}, False def delete_db(self): if self.database.exists(): self.client.delete_database(USER_DB) def insert_document(self, key, data): # First retrieve the document document, err = self.get_document(key) if err: logger.info('Document not found, will create it with key=%s' % key) return self.create_document(data) # Update the document content # This can be done as you would any other dictionary for key in data: try: document[key] = data[key] except: logger.warning('Key %s missing in document %s' % (key, document)) # You must save the document in order to update it on the database document.save() logger.info('Success, document id=%s, new rev=%s' % (document['_id'], document['_rev'])) return '{"_id"="%s", "_rev":"%s"}' % (document['_id'], document['_rev']), False def create_document(self, data): if '_id' not in data: logger.error('No "_id" field in document') return 'No "_id" field in document', True document = self.database.create_document(data) if document.exists(): return document['_id'], False logger.error('Failed to create document %s' % data) return 'Failed to create document', True def create_report_metadata(self, data): if '_id' not in data: logger.error('No "_id" field in document') return 'No "_id" field in document', True document = self.acl_db.create_document(data) if document.exists(): return document['_id'], False logger.error('Failed to create document %s' % data) return 'Failed to create document', True def get_document(self, key): try: document = self.database[key] except: logger.error('Failed to retrieve document with key=%s' % key) return 'Failed to retrieve document with key=%s' % key, True logger.info('Got document %s' % document) return document, False def get_report_metadata(self, key): try: document = self.acl_db[key] except: logger.error('Failed to retrieve document with key=%s' % key) return 'Failed to retrieve document with key=%s' % key, True logger.info('Got document %s' % document) return document, False def update_document(self, key, data): # First retrieve the document document, err = self.get_document(key) if err: logger.error('Failed to update document with key=%s' % key) return 'Failed to update document with key=%s' % key, True # Update the document content # This can be done as you would any other dictionary for key in data: try: document[key] = data[key] except: logger.warning('Key %s missing in document %s' % (key, document)) # You must save the document in order to update it on the database document.save() logger.info('Success, document id=%s, new rev=%s' % (document['_id'], document['_rev'])) return '{"_id"="%s", "_rev":"%s"}' % (document['_id'], document['_rev']), False def delete_document(self, key): # First retrieve the document document, err = self.get_document(key) if err: logger.error('Failed to delete document with key=%s' % key) return 'Failed to delete document with key=%s' % key, True document.delete() logger.info('Success, deleted document key=%s' % key) return 'Success, deleted document key=%s' % key, False