def getDb(): # credential to cloudant c4c2020 api_access = { "apikey": "nTFpLxd6ufHJrwzzUbPPd_2G9wqhIx0_Twa9LqQH691U", "host": "61d79bba-2f14-46da-b1a3-eacc3848d4ff-bluemix.cloudantnosqldb.appdomain.cloud", "iam_apikey_description": "Auto-generated for key 63a548a5-93c8-42d6-8eb2-ba4fc644dac7", "iam_apikey_name": "Service credentials-1", "iam_role_crn": "crn:v1:bluemix:public:iam::::serviceRole:Manager", "iam_serviceid_crn": "crn:v1:bluemix:public:iam-identity::a/0a7e44c4d4d86c8f9a2f8ff4cc400f87::serviceid:ServiceId-e871c59c-7908-45b0-93fb-9898a5b496b5", "url": "https://61d79bba-2f14-46da-b1a3-eacc3848d4ff-bluemix.cloudantnosqldb.appdomain.cloud", "username": "******" } # client = Cloudant.iam(ACCOUNT_NAME, API_KEY, connect=True) client = Cloudant.iam(api_access['username'], api_access['apikey'], connect=True) # Create a database using an initialized client # The result is a new CloudantDatabase or CouchDatabase based on the client db = client.create_database('database') # You can check that the database exists if db.exists(): print('SUCCESS!! Client object db is created.') db = client['database'] else: print('FAIL!! No client object is created.') db = None return db
def html_table(): if request.form['submit_button'] == 'Do Something': client = Cloudant.iam("4a366964-f520-4ba2-afba-9a1b374f4277-bluemix", "4FpjCCjAVftwY8ZLZDSUJa_8iG14u0c0VsXPB-YEhrU6", connect=True) g = session.get("globaldb") my_database = client[g] l = [] for document in my_database: l.append(document) df = pd.DataFrame(l) del df['_id'] del df['_rev'] # del df['tp_login'] # del df['tp_pass'] del df['form_filled'] cols = [ "tp_name", "VAN_or_AS2", "contact_person", "email_id", "status" ] df = df[cols] df['VAN_or_AS2'].value_counts().plot(kind='bar') fig = Figure() axis = fig.add_subplot(1, 1, 1) axis.set_title("Number of VAN and AS2") axis.grid() bd = df['VAN_or_AS2'].value_counts() b = dict(bd) axis.bar(b.keys(), b.values(), width=0.2, align='edge') pngImage = io.BytesIO() FigureCanvas(fig).print_png(pngImage) pngImageB64String = "data:image/png;base64," pngImageB64String += base64.b64encode( pngImage.getvalue()).decode('utf8') fig = Figure() axis = fig.add_subplot(1, 1, 1) axis.set_title("Project status ") axis.grid() labels = [] sizes = [] bd = df['status'].value_counts() b = dict(bd) for x, y in b.items(): labels.append(x) sizes.append(y) patches, texts = axis.pie(sizes, labels=labels) axis.legend(patches, labels, loc="best") pngImage = io.BytesIO() FigureCanvas(fig).print_png(pngImage) pngImageB64String1 = "data:image/png;base64," pngImageB64String1 += base64.b64encode( pngImage.getvalue()).decode('utf8') return render_template('new.html', tables=[ df.to_html(classes='data', table_id='htmltable', index=False) ], image=pngImageB64String, image1=pngImageB64String1)
def getTweetAtIndex(index, location, key = "tweet"): client = Cloudant.iam("fc535eaf-52c1-47a3-acf6-c990cfa80dfd-bluemix", "AWLmt1r-iqtEeWTDjEC38l320ufQGsFAheg40iutvxcB") client.connect() url = "https://*****:*****@fc535eaf-52c1-47a3-acf6-c990cfa80dfd-bluemix.cloudantnosqldb.appdomain.cloud" end_point = '{0}/{1}'.format(url, location + "_database" + "/_all_docs") params = {'include_docs': 'true'} response = client.r_session.get(end_point, params=params) return response.json()["rows"][index]["doc"][key]
def __init__(self): """Connect to database.""" self.client = cloudant.iam(USERNAME, APIKEY, timeout=5, adapter=HTTPAdapter(max_retries=RETRIES)) self.client.connect() self.db = self.client[DATABASE]
def insertTweet(database, text, probability): client = Cloudant.iam("fc535eaf-52c1-47a3-acf6-c990cfa80dfd-bluemix", "AWLmt1r-iqtEeWTDjEC38l320ufQGsFAheg40iutvxcB") client.connect() jsonDoc= { "tweet": text, "probability": probability } database.create_document(jsonDoc) return
def getDBdoc(param, id, db): db_username = param['username'] api = param['api'] databaseName = db client = Cloudant.iam(db_username, api, connect=True) myDatabaseDemo = client[databaseName] db_doc = myDatabaseDemo[id] return db_doc
def ibm_auth(): key = read_key_info( ) #read info from device_info.json; ref "change_device_info.py" api_info = authenticate.api_key_request( key["namespace"], key["passpharse"]) # invoke cloud function; ref "authenticate.py" username = api_info["user_name"] api_key = api_info["api_key"] return Cloudant.iam(username, api_key, connect=True) #login to cloudent DB
def get_cloudant_account(params): if not 'api_username' in params: return "api_username parameter is required." if not 'api_key' in params: return "api_key parameter is required." from cloudant.client import Cloudant return Cloudant.iam(params['api_username'], params['api_key'], connect=True)
def __init__(self, username, api_key): """ Constructor de la conexión a IBM cloudant Args: username (str): usuario. apikey (str): API key. """ self.connection = Cloudant.iam(username, api_key, connect=True) self.connection.connect()
def get_cloudant_doc(itemID): client = Cloudant.iam(app.config["USER"], app.config["APIKEY"], connect=True) client.connect() database = CloudantDatabase(client, "marketplace-history-database") with Document(database, document_id=f"marketplace-history-{itemID}") as document: return (document)
def getUser(): client = Cloudant.iam("d02a0070-4a25-4e81-b712-a8e6c38a8863-bluemix", "0CpvlhxnS58tIZMsdu4QuUqw4bai6t1EYcJAv4Mo4lnI") client.connect() database_name = "user_db" # print(client.all_dbs()) db = client[database_name] #open database # print(db) userDoc = db["user1"] return userDoc
def __init__(self,cloudName="aws",event=None): self.cloudName = cloudName # if self.cloudName == "aws": # self.db = boto3.client('dynamodb') if self.cloudName == "openwhisk": self.host = "d59c484b-77e6-4236-ae6c-e3e9c499b8ea-bluemix" self.key = os.environ['__OW_IAM_NAMESPACE_API_KEY'] self.db = Cloudant.iam(self.host,self.key)
def saveTickers(tickers): client = Cloudant.iam("d02a0070-4a25-4e81-b712-a8e6c38a8863-bluemix", "0CpvlhxnS58tIZMsdu4QuUqw4bai6t1EYcJAv4Mo4lnI") client.connect() database_name = "user_db" # print(client.all_dbs()) db = client[database_name] #open database print(db) userDoc = db["user1"] userDoc['tickers'] = tickers userDoc.save()
def getall(param, db): db_username = param['username'] api = param['api'] databaseName = db client = Cloudant.iam(db_username, api, connect=True) myDatabaseDemo = client[databaseName] dic = {} i = 0 for document in myDatabaseDemo: dic[i] = document["_id"] i = i + 1 return dic
def save_loc_to_db(user, location): client = Cloudant.iam("", "") client.connect() db = client["test"] loc = json.loads(location) data = {"user": user, "lastLat": loc['lat'], "lastLng": loc['lng']} doc = db.create_document(data) client.disconnect()
def init(): # This is the name of the database we are working with. databaseName = "persons_db" client = Cloudant.iam(this.__username__, this.__apiKey__) client.connect() myDatabase = client.create_database(databaseName) if not myDatabase.exists(): # IDK, raise some error or panic client.create_database(databaseName) this.__client__ = client this.__myDatabase__ = myDatabase
def test_iam_client_session_login(self, m_set, m_login): # create IAM client client = Cloudant.iam('foo', MOCK_API_KEY) client.connect() # add a valid cookie to jar client.r_session.cookies.set_cookie(self._mock_cookie()) client.session_login() m_set.assert_called_with(None, None) self.assertEqual(m_login.call_count, 2) self.assertEqual(m_set.call_count, 2)
def test_iam_client_session_login_with_new_credentials(self, m_set, m_login): # create IAM client client = Cloudant.iam('foo', MOCK_API_KEY) client.connect() # add a valid cookie to jar client.r_session.cookies.set_cookie(self._mock_cookie()) client.session_login('bar', 'baz') # new creds m_set.assert_called_with('bar', 'baz') self.assertEqual(m_login.call_count, 2) self.assertEqual(m_set.call_count, 2)
def download2(): if request.form['submit_button6'] == 'download': client = Cloudant.iam("4a366964-f520-4ba2-afba-9a1b374f4277-bluemix", "4FpjCCjAVftwY8ZLZDSUJa_8iG14u0c0VsXPB-YEhrU6", connect=True) g = session.get("cust_db") c = session.get("customer_report") c = c.decode("utf-8") my_database = client[g] l = [] for document in my_database: l.append(document) df = pd.DataFrame(l) del df['_id'] del df['_rev'] cols = [ "tp_name", "VAN_or_AS2", "contact_person", "email_id", "status" ] df = df[cols] with PdfPages('report.pdf') as pp: fig, (ax, ax1, ax2) = plt.subplots(3, 1, figsize=(10, 15)) #figsize=(12,4) ax.set_title("Project Reports of Trading Partners of " + c) ax.axis('tight') ax.axis('off') the_table = ax.table(cellText=df.values, colLabels=df.columns, loc='center', cellLoc='left', colLoc='left') ax1.set_title("Number of VAN and AS2") ax1.grid() bd = df['VAN_or_AS2'].value_counts() b = dict(bd) ax1.bar(b.keys(), b.values(), width=0.2, align='edge') ax2.set_title("Project status ") ax2.grid() labels = [] sizes = [] bd = df['status'].value_counts() b = dict(bd) for x, y in b.items(): labels.append(x) sizes.append(y) patches, texts = ax2.pie(sizes, labels=labels) ax2.legend(patches, labels, loc="best") pp.savefig(fig, bbox_inches='tight') plt.close() path = "report.pdf" return send_file(path, as_attachment=True)
def __init__(self): # type: () -> None creds = config.db_creds print(creds) print("connecting to Db with username {0} and password {1}".format( os.getenv('DB_USERNAME'), os.getenv("DB_API_KEY"))) if creds['username'] and creds['apikey']: self.client = Cloudant.iam(creds['username'], creds['apikey'], connect=True) # os.getenv('DB_USERNAME'), os.getenv("DB_API_KEY"), connect=True) self.db = self.init_db() else: print("No DB creds, not connected to DB")
def call_add_account(account_info): # set up ACCOUNT_NAME = "f5bdda05-9289-4541-9665-0290ff2dd594-bluemix" API_KEY = "z_YFZaGQ3JmiXrLccCmqV8SeWxJz-SlMCiazZjB6aM6r" #create client client = Cloudant.iam(ACCOUNT_NAME, API_KEY, connect=True) client.connect() #creating database within the service instance if not already exist databaseName = "accounts" client.create_database(databaseName) add_account(client, databaseName, account_info)
def calculateLocationEarthquakeProbability(location): client = Cloudant.iam("fc535eaf-52c1-47a3-acf6-c990cfa80dfd-bluemix", "AWLmt1r-iqtEeWTDjEC38l320ufQGsFAheg40iutvxcB") client.connect() url = "https://*****:*****@fc535eaf-52c1-47a3-acf6-c990cfa80dfd-bluemix.cloudantnosqldb.appdomain.cloud" end_point = '{0}/{1}'.format(url, location + "_database" + "/_all_docs") params = {'include_docs': 'true'} response = client.r_session.get(end_point, params=params) probabilities = [] for i in range(10): probabilities.append(response.json()["rows"][i]["doc"]["probability"]) file = open("earthquakeProbability.sav", 'rb') earthquakeRegressor = pickle.load(file) file.close() return earthquakeRegressor.predict([probabilities])
def accountSetUp(username, password): client = Cloudant.iam("d02a0070-4a25-4e81-b712-a8e6c38a8863-bluemix", "0CpvlhxnS58tIZMsdu4QuUqw4bai6t1EYcJAv4Mo4lnI") client.connect() database_name = "user_db" # print(client.all_dbs()) db = client[database_name] #open database print(db) userDoc = db["user1"] print(userDoc) userDoc['username'] = username userDoc['password'] = password ## make calls to ncr stuff and return back user dictionary userDoc['userData'] = {} #replace this later with user object akshay makes userDoc.save()
def initServices(app): # Setup MQTT app.config['MQTT_BROKER_URL'] = 'test.mosquitto.org' app.config['MQTT_BROKER_PORT'] = 1883 mqtt = Mqtt(app) app.config['MQTT_CLIENT'] = mqtt app.config['TEMP_FOLDER'] = "public/img" # Setup Cloudant client = Cloudant.iam("93be668d-82a1-4b5e-aeaa-70dcd895b019-bluemix", "IMkPio4zsgC7zmYmcmp6tL1ueCqbT65cawkXG4bS9JOS", connect=True) app.config['CLOUDANT'] = client # Setup IBM Watson load_dotenv() # IBM COS app.config['COS_ENDPOINT'] = os.getenv("COS_ENDPOINT") if not app.config['COS_ENDPOINT'].startswith( 'http') or not app.config['COS_ENDPOINT'].startswith('https'): app.config['COS_ENDPOINT'] = 'https://' + app.config['COS_ENDPOINT'] cos = ibm_boto3.resource( "s3", ibm_api_key_id=os.getenv("COS_API_KEY"), ibm_service_instance_id=os.getenv("COS_IAM_ROLE_CRN"), ibm_auth_endpoint='https://iam.cloud.ibm.com/identity/token', config=Config(signature_version="oauth"), endpoint_url=app.config['COS_ENDPOINT']) app.config['COS'] = cos app.config['COS_BUCKET_NAME'] = os.getenv("COS_BUCKET_NAME") # Setup config app.config['BASE'] = os.path.join( os.path.dirname(os.getcwd()), 'cfc-covid-19-video-transcriber-starter') app.config['BASE'] = os.path.join(app.config['BASE'], 'server') app.config['UPLOAD_FOLDER'] = os.path.join(app.config['BASE'], 'video_uploads') app.config['AUDIO_FOLDER'] = os.path.join(app.config['BASE'], 'audio_extractions') app.config['OUTPUT_FOLDER'] = os.path.join(app.config['BASE'], 'output_transcripts') os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) os.makedirs(app.config['AUDIO_FOLDER'], exist_ok=True) os.makedirs(app.config['OUTPUT_FOLDER'], exist_ok=True) return
def check_login(username, password): client = Cloudant.iam("", "") client.connect() database_name = "test" my_database = client[database_name] for d in my_database: username_db = d["username"] password_db = d["password"] if username == username_db and password == password_db: print(json.dumps(d)) client.disconnect() return print('Could not find account', file=sys.stderr) client.disconnect()
def init(): client = Cloudant.iam(this.__username__, this.__apiKey__) client.connect() userDatabase = client.create_database(this.userDatabaseName) if not userDatabase.exists(): # IDK, raise some error or panic client.create_database(this.userDatabaseName) hospitalDatabase = client.create_database(this.hospitalDatabaseName) if not userDatabase.exists(): # IDK, raise some error or panic client.create_database(this.hospitalDatabaseName) this.__client__ = client this.__userDatabase__ = userDatabase this.__hospitalDatabase__ = hospitalDatabase
def main(dict): dict = dict["post_id"] client = Cloudant.iam("3205c8bb-12e8-4e6b-b669-fbe872bf29df-bluemix", "oxXUO9-AR5XOCXcQ9EJaVtIAY9DLPx77eUFCv2yrChqL", connect=True) client.connect() database_name = "auxilium" my_database = client.create_database(database_name) if my_database.exists(): # Create a new document my_document = my_database[dict] my_document.delete() return {"message": "success"}
def main(dict): client = Cloudant.iam("3205c8bb-12e8-4e6b-b669-fbe872bf29df-bluemix", "oxXUO9-AR5XOCXcQ9EJaVtIAY9DLPx77eUFCv2yrChqL", connect=True) client.connect() database_name = "user" my_database = client.create_database(database_name) if my_database.exists: if dict['user_id'] in my_database: my_document = my_database[dict['user_id']] return {'data': my_document} else: my_document = my_database.create_document(dict['data']) if my_document.exists(): return {'data': my_document}
def add_family_members(username,password,name,number): client = Cloudant.iam("","") client.connect() database_name = "test" my_database = client[database_name] for document in my_database: username_db = document["username"] password_db = document["password"] if username == username_db and password == password_db: document['preferences']['family_numbers'].append({number:name}) document.save() print("Family member's phone number info pushed to document in database") break else: print("User not found") client.disconnect()
def add_coordinates(username,password,lat,lng): client = Cloudant.iam("","") client.connect() database_name = "test" my_database = client[database_name] for document in my_database: username_db = document["username"] password_db = document["password"] if username == username_db and password == password_db: document['coordinates'].append([{"lat": lat},{"lng": lng},{"timestamp":str(datetime.datetime.now())}]) document.save() print('Coordinates pushed to document in database') break else: print("User not found") client.disconnect()