def read_status_from_cloudant(device_id, field): user_data = get_user_data() client = Cloudant(user_data['cloud_acct_username'], user_data['cloud_acct_pword'], url=user_data['cloud_act_url']) client.connect() my_database = client["system_status"] my_document = my_database[device_id] value = my_document[field] return current_temp, current_time
def conn(): 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'] # print(cl_username + ' ' + cl_password) client = Cloudant(cl_username, cl_password, url=url) client.connect() session = client.session() # print 'Username: {0}'.format(session['userCtx']['name']) # print 'Databases: {0}'.format(client.all_dbs()) return client
def worker(num, s3_client): print("Running worker %s" % num) season = 2017 num_to_sport = {0: 'mlb', 1: 'nba', 2: 'nhl'} sport = num_to_sport[num] all_teams = teams[sport] size_data = [] for team in all_teams: print("Collecting for %s" % team) size_data.append(get_s3_metadata(s3_client, sport, season, team)) if 'VCAP_SERVICES' not in os.environ: from functions.credentials import * cloudant_client = Cloudant(CLOUDANT['username'], CLOUDANT['password'], url=CLOUDANT['url'], connect=True, auto_renew=True) else: vcap = json.loads(os.getenv('VCAP_SERVICES')) if 'cloudantNoSQLDB' in vcap: creds = vcap['cloudantNoSQLDB'][0]['credentials'] user = creds['username'] password = creds['password'] url = 'https://' + creds['host'] cloudant_client = Cloudant(user, password, url=url, connect=True) write_doc(cloudant_client, size_data, sport)
def test_constructor_with_creds_removed_from_url(self): """ Test instantiating a client object using a URL """ client = Cloudant(None, None, url='https://a9a9a9a9-a9a9-a9a9-a9a9-a9a9a9a9a9a9-bluemix' ':a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9' 'a9a9a9a9a9a9@d8a01891-e4d2-4102-b5f8-751fb735ce31-' 'bluemix.cloudant.com') self.assertEqual(client.server_url, 'https://d8a01891-e4d2-4102-b5f8-751fb735ce31-' 'bluemix.cloudant.com') self.assertEqual(client._user, 'a9a9a9a9-a9a9-a9a9-a9a9-a9a9a9a9a9a9-bluemix') self.assertEqual(client._auth_token, 'a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a' '9a9a9a9a9a9a9a9a9a9a9a9a9')
def backyard_read_temp_from_cloudant(device_id): user_data = get_user_data() client = Cloudant(user_data['cloud_acct_username'], user_data['cloud_acct_pword'], url=user_data['cloud_act_url']) client.connect() my_database = client["system_status"] my_document = my_database[device_id] current_temp = my_document['v'] current_time = dt.datetime.strptime(my_document['t'], "%H:%M:%S") current_time = current_time.strftime("%I:%M %p") return current_temp, current_time
def AntecedentesApiGet(request, cc): client = Cloudant( '0fe5f2c7-b763-4636-a768-6eb9ed79b1c6-bluemix', 'd5fb4bdd9bdeb36d09224085e367317c4013b9ec5e65f8889efdc40621bbc9c8', url= 'https://*****:*****@0fe5f2c7-b763-4636-a768-6eb9ed79b1c6-bluemix.cloudant.com', connect=True) client.connect() db = client['ctrata'] document = db["perfiles"] r = str(cc) in document client.disconnect() return HttpResponse(r)
def salvarAnimes(request, path='/animes/A'): if request.method == 'POST': db = Cloudant(USUARIO_DB, SENHA_DB, url=URL, connect=True)['ahs'] doc = db[request.POST.get('id')] doc['recomendado'] = mudarAtributoInt( request.POST.get('recomendar_anime')) doc['disponibilizar'] = mudarAtributoInt( request.POST.get('disponibilizar_anime')) doc['fansub'] = request.POST.get('fansub') doc.save() return redirect(path)
def index(request): db = Cloudant(USUARIO_DB, SENHA_DB, url=URL, connect=True)['ahs'] ultimos_animes_adicionados = View(db['_design/ahs'], 'ultimos_adicionados') #Cria Contexto de retorno contexto = {} contexto['animes_recomendados'] = db.get_view_result( '_design/ahs', 'ani-recomendados') contexto['ultimos_lancamentos'] = ultimos_animes_adicionados( include_docs=True, descending=True, limit=10)['rows'] contexto['alfabeto'] = alfabeto return render(request, 'index.html', contexto)
def __init__(self): env = json.loads(os.getenv("VCAP_SERVICES")) username = env["cloudantNoSQLDB"][0]["credentials"]["username"] password = env["cloudantNoSQLDB"][0]["credentials"]["password"] host = env["cloudantNoSQLDB"][0]["credentials"]["host"] url = env["cloudantNoSQLDB"][0]["credentials"]["url"] port = int(env["cloudantNoSQLDB"][0]["credentials"]["port"]) client = Cloudant(username, password, host=host, url=url, port=port, ) client.connect() self.db = client["test_db"]
def start_historic(request): regex_result = re.search( "startStream\?csv=([a-z,A-Z,0-9,_-]+)\.csv&json=([a-z,A-Z,0-9,_-]+)\.json&question=([a-z,A-Z,0-9,\+_-]+)", request) if regex_result is None: print("Failed to find specified Files") return 0 else: try: print("Question: " + regex_result.group(3)) except: print("Failed to find Question asked") return 0 #check if we run on bluemix if 'VCAP_SERVICES' in os.environ: vcap_servicesData = json.loads(os.environ['VCAP_SERVICES']) else: print("On Local PC") json_file = open("vcap-local.json") s = json_file.read() vcap_servicesData = json.loads(s) vcap_servicesData = vcap_servicesData[u'services'] # Connect To Cloudant DB cloudantNoSQLDBData = vcap_servicesData[u'cloudantNoSQLDB'] credentials = cloudantNoSQLDBData[0] credentialsData = credentials[u'credentials'] serviceUsername = credentialsData[u'username'] servicePassword = credentialsData[u'password'] serviceURL = credentialsData[u'url'] client = Cloudant(serviceUsername, servicePassword, url=serviceURL) client.connect() database_json = client['incoming_warning'] t = str(int(time.time())) #jfile = t + ".json" #cfile = t + ".csv" json_db = { u"json-file": regex_result.group(2) + ".json", u"csv-file": regex_result.group(1) + ".csv", u"question": regex_result.group(3), u"Time-in": t } newDocument = database_json.create_document(json_db) client.disconnect() return 1
def start(): while (1): try: #check if we run on bluemix if 'VCAP_SERVICES' in os.environ: vcap_servicesData = json.loads(os.environ['VCAP_SERVICES']) else: print("On Local PC") json_file = open("static/vcap-local.json") s = json_file.read() vcap_servicesData = json.loads(s) vcap_servicesData = vcap_servicesData[u'services'] # Connect To Cloudant DB cloudantNoSQLDBData = vcap_servicesData[u'cloudantNoSQLDB'] credentials = cloudantNoSQLDBData[0] credentialsData = credentials[u'credentials'] serviceUsername = credentialsData[u'username'] servicePassword = credentialsData[u'password'] serviceURL = credentialsData[u'url'] client = Cloudant(serviceUsername, servicePassword, url=serviceURL) client.connect() database_json = client['incoming_warning'] new_csv = [] new_json = [] new_question = [] for doc in database_json: new_json.append(doc[u'json-file']) new_csv.append(doc[u'csv-file']) new_question.append(doc[u'question']) doc.delete() client.disconnect() #Run Processing if ((len(new_csv) == 1) and (len(new_json) == 1) and (len(new_question) == 1)): print("Found new data") result = main(new_json[0], new_csv[0], new_question[0]) save_data(result) elif ((len(new_csv) > 1) or (len(new_json) > 1) or (len(new_question) > 1)): print("ERROR") # This is currently an issue we will fix this later else: time.sleep(1) except KeyboardInterrupt: print("done runing") return 0 return 0
def get_db_client(db_name: str = None): db_config = config.get('db') user = db_config.get('user') passwd = db_config.get('password') db_list = os.environ.get('dbip') if db_list: db_list = db_list.split(',') connected = False for ip in db_list: try: url = 'http://%s' % ip client = Cloudant(user, passwd, url=url, connect=True, auto_renew=True) connected = True break except: print("connect %s failed" % url) if not connected: print("cannot connect to db, exiting") sys.exit(1) else: url = db_config.get('url') try: client = Cloudant(user, passwd, url=url, connect=True, auto_renew=True) except: print("cannot connect to db, exiting") sys.exit(1) db_name = db_config.get('db') if db_name is None else db_name return client[db_name]
def ListFiles(): client = Cloudant("accesS_key","secret key", url='url') client.connect() session = client.session() print 'Username: {0}'.format(session['userCtx']['name']) print 'Databases: {0}'.format(client.all_dbs()) my_database = client['test'] ## Get all of the documents from my_database t = HTML.Table(header_row=['File Name', 'File Version', 'Last Modified Date']) for document in my_database: t.rows.append([document['name'],document['version'],document['Last_Modified_Date']]) htmlcode = str(t) return htmlcode
def get_client(connection: CouchDbConnection): if (connection.url, connection.user) not in CouchDbConnectionPool.connection_dict: conn = Cloudant(connection.user, connection.token, url=connection.url, connect=True, auto_renew=True) CouchDbConnectionPool.connection_dict[(connection.url, connection.user)] = conn return conn else: return CouchDbConnectionPool.connection_dict[(connection.url, connection.user)]
def the_bar_graph_routing(): x=[] y=[] p=figure(title="X-axis Gravity Sensor values v/s time",x_axis_label='time',y_axis_label='gravity_x') client=Cloudant("<user_id>","<password>",url="<db_url>") client.connect() myDatabase = client['sample_db'] result_collection = Result(myDatabase.all_docs,include_docs=True) for i in result_collection: x.append(i['doc']['payload']['time']) y.append(i['doc']['payload']['gravity_x']) p.vbar(x=x,top=y,width=0.9) script, div = components(p) return render_template("mod_chart.html",div=div, script=script)
def connect(self, db_url, username=None, auth_token=None): """ Connect to the Cloudant DB """ if isinstance(self.connection, Cloudant): return self.connection = Cloudant( cloudant_user=username, auth_token=auth_token, url=db_url, connect=True, use_basic_auth= True # FYI: Well, it took time to figure out, how to skip Cookie auth and user&passwd :) )
def consultarCloudant(): # Authenticate using an IAM API key client = Cloudant(CLOUDANT_USERNAME, CLOUDANT_PASSWORD, url=CLOUDANT_URL, connect=True) session = client.session() # print('Username: {0}'.format(session['userCtx']['name'])) # print('Databases: {0}'.format(client.all_dbs())) result_collection = Result(client["prueba"].all_docs, include_docs=True) print("Retrieved minimal document:\n{0}\n".format(result_collection[0])) # Disconnect from the server client.disconnect() return result_collection
def buscaAnimes(request): if request.method == 'POST': db = Cloudant(USUARIO_DB, SENHA_DB, url=URL, connect=True)['ahs'] selector = { "titulo_pesquisa": { "$regex": request.POST.get('texto_para_pesquisa').lower() } } contexto = {} contexto['resultado'] = db.get_query_result(selector) contexto['alfabeto'] = alfabeto return render(request, 'buscaPorNomes.html', contexto)
def main(data, id): global client global dbname dbhost = "https://" + "2080e923-0239-4314-843c-505bc43a74c2-bluemix" + ".cloudant.com" client = Cloudant( "2080e923-0239-4314-843c-505bc43a74c2-bluemix", "91cda9f0ff213a2bdb204dd1c5100b5e54d664b4e0175ad0ea7294b11304dd37", url=dbhost, connect=True) dbname = "siata" my_database = client[dbname] updateDocument(data, id) client.disconnect()
def connect_to_db(cls): if cls.db_client is not None: logging.fatal("Tried to start a new DB connection" " while already connected.") raise TypeError("Tried to start a new DB connection" " while already connected.") adapter = Replay429Adapter(200, 0.25) cls.db_client = Cloudant(cls.api_user, cls.api_pass, url=cls.api_url, adapter=adapter) cls.db_client.connect() cls.courses_db = cls.db_client['purdue_courses'] cls.courses_db.all_docs logging.info("Cloudant connection is live.")
def check_timing(self): client = Cloudant(self.readuser, self.readpass, url=self.url, connect=True, auto_renew=True) prices_db = client['stock-prices'] pricequery = Query(prices_db, selector={'symbol': self.ticker}) try: prices = pricequery()['docs'][0]['Meta Data']['3. Last Refreshed'] except IndexError: prices = False return {'ticker': self.ticker, 'prices': prices}
def generate_records(start_date, end_date): database_name = "blueprint_db" server_url = "http://127.0.0.1:5984" username = None password = None design_doc = "_design/blueprintmetric" view_name = "blueprintcloudpakmetric" client = Cloudant(username, password, url=server_url, admin_party=True, connect=True) db_obj = database.CloudantDatabase(client, database_name) res = db_obj.get_view_result(design_doc, view_name, raw_result=True, include_docs=True, reduce=False) final_res = [] for row in res['rows']: print(row['doc']['_id']) cr_at = (row['doc']['created_at']) print(cr_at[:11]) cr_at = datetime.datetime.strptime(cr_at[:10], '%Y-%m-%d') if cr_at >= start_date and cr_at <= end_date: entry = { "account":row['doc']['account'], "workspace_id":row['doc']['_id'], "workspace_status":row['doc']['status'], "workspace_region" : row['doc']['location'], "workspace_createdDate": row['doc']['created_at'], "offering_installed_on" : row['doc']['runtime_data'][0]['created_on'], "offering_destroyed_on" : row['doc']['runtime_data'][0]['destroyed_on'], "Offering_name" : row['doc']['catalog_ref']['item_name'], "Offering_id" : row['doc']['catalog_ref']['item_id'], "Offering_url" : row['doc']['catalog_ref']['item_url'], "Offering_version" : row['doc']['catalog_ref']['offering_version'], "cluster_id":row['doc']['shared_data']['cluster_id'], "cluster_type" : row['doc']['shared_data']['cluster_type'], "cluster_worker_count": row['doc']['shared_data']['worker_count'], "cluster_worker_machine_type" : row['doc']['shared_data']['worker_machine_type'], "cluster_created_on" : row['doc']['shared_data']['cluster_created_on'], "cluster_region" : row['doc']['shared_data']['region'] } final_res.append(entry) dataframe = pandas.DataFrame(final_res) df = dataframe.sort_values("offering_installed_on", ascending=False) print(df) df.to_csv("CloudPak-{}.csv".format(datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S")), index=False) # Disconnect from the server client.disconnect()
def looping(): while True: time.sleep(5) ser = serial.Serial("/dev/ttyACM0", 9600) ser.baudrate = 9600 temp1 = ser.readline() # temp1 = 20 ser = serial.Serial("/dev/ttyACM1", 9600) ser.baudrate = 9600 temp2 = ser.readline() # temp2 = 20 print temp1, temp2 if int(temp1[0:2]) < 35: # if temp1 < 35: l1['color'] = "#2ecc71" l1['Safe'] = "true" else: l1['color'] = "#c0392b" l1['Safe'] = "false" # if temp2 < 35: if int(temp2[0:2]) < 35: l2['color'] = "#2ecc71" l2['Safe'] = "true" else: l2['color'] = "#c0392b" l2['Safe'] = "false" serviceUsername = "******" servicePassword = "******" serviceURL = "https://*****:*****@ac99bfe8-c64e-48a5-9f62-e3b7c44ba586-bluemix.cloudant.com" client = Cloudant(serviceUsername, servicePassword, url=serviceURL) client.connect() databaseName = "sensordbs" try: client.delete_database(databaseName) except CloudantException: print "There was a problem deleting '{0}'.\n".format(databaseName) else: print "'{0}' successfully deleted.\n".format(databaseName) myDatabaseDemo = client.create_database(databaseName) if myDatabaseDemo.exists(): print "'{0}' successfully created.\n".format(databaseName) newDocument = myDatabaseDemo.create_document(l1) newDocument = myDatabaseDemo.create_document(l2) # Check that the document exists in the database. if newDocument.exists(): print "Document"
def __init__(self, cloudant_dialogname, cloudant_password, cloudant_url, db_name): """ Creates a new instance of CloudantDialogStore. Parameters ---------- cloudant_dialogname - The dialogname for the cloudant instance cloudant_password - The password for the cloudant instance cloudant_url - The url of the of cloudant instance to connect to db_name - The name of the database to use """ if cloudant_url.find('@') > 0: prefix = cloudant_url[0:cloudant_url.find('://')+3] suffix = cloudant_url[cloudant_url.find('@')+1:] cloudant_url = '{}{}'.format(prefix, suffix) self.client = Cloudant(cloudant_dialogname, cloudant_password, url=cloudant_url) self.db_name = db_name
def connect_cloudant(): is_bluemix_env = os.getenv("cloudant_env") == "bluemix" global __cloudant_client__ if is_bluemix_env: with cloudant_bluemix( os.getenv("VCAP_SERVICES")) as __cloudant_client__: print("connected to cloudant bluemix service!!") else: __cloudant_client__ = Cloudant("admin", "pass", url="http://localhost:7080", connect=True, auto_renew=True) print("connected to local cloudant instance!!")
def connect(url): try: global cc, all_dbs cc = Cloudant(os.environ['COUCHUSER'], os.environ['COUCHPASS'], url=url, connect=True) all_dbs = cc.all_dbs() except KeyError: logging.error( 'please configure the COUCHUSER and COUCHPASS environment variables' ) exit(1) except Exception as e: logging.error('unable to connect to CouchdB', e) exit(1)
def __init__(self): common = Common() global cloudantInfo,dbInfo,env,mydb,client appConfig=common.readJson('config') if 'VCAP_SERVICES' in os.environ and 'cloudantNoSQLDB' in json.loads(os.getenv('VCAP_SERVICES')): vcap = json.loads(os.getenv('VCAP_SERVICES')) cloudantInfo = vcap['cloudantNoSQLDB'][0]['credentials'] else: cloudantInfo=appConfig['CLOUDANT'] client = Cloudant(cloudantInfo['username'], cloudantInfo['password'], url=cloudantInfo['url'], adapter=Replay429Adapter(retries=20, initialBackoff=0.1), connect=True, auto_renew=True) dbInfo = appConfig['DATABASE'] env = appConfig['ENVIRONMENT'] mydb = self.getDatabase(dbInfo[env])
def __enter__(self): """ Runs when the control flow enters the with() statement. Creates the Cloudant client instant and the Cloudant database instant. To connect to the world readable database, I had to use the 'admin_party' flag. """ self.client = Cloudant(" ", " ", admin_party=True, url=self.url, connect=True) self.db = CloudantDatabase(self.client, self.db_name) return self
def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self._homeDir = os.path.expanduser("~/.sensomatic") self._configFileName = self._homeDir + '/config.ini' self._config = ConfigParser.ConfigParser() self._readConfig() self._redis = redis.StrictRedis( host=self._config.get("REDIS", "ServerAddress"), port=self._config.get("REDIS", "ServerPort"), db=0) self._cloudant = Cloudant(self._config.get("CLOUDANT", "Username"), self._config.get("CLOUDANT", "Password"), url=self._config.get("CLOUDANT", "ServerAddress")) self.checkDB()
def upload_inconsistencies(inconsistencies_list): user = os.getenv("USER") password = os.getenv("PASSWORD") url = os.getenv("URL") db_name = os.getenv("INCONSISTENCY_DB") client = Cloudant(user, password, url=url, connect=True, auto_renew=True) # Open inconsistency DB inconsistency_db = client[db_name] try: for inconsistency in inconsistencies_list: inconsistency_db.create_document(vars(inconsistency)) except Exception as e: print(e) # Disconnect from the server client.disconnect()