def get_client() -> cloudant.Cloudant: return cloudant.Cloudant( "admin", "password", url="http://127.0.0.1:5984", connect=True, )
def verifyUser(username, password, role): #Verify the user/pass combination #Calculate hashed password salt = uuid.uuid4().hex hashed_password = hashlib.sha512(str(password + salt).encode('utf-8')).hexdigest() #Begin accessing the database cloudant_api_key = "bsideentsamedgediabsidst" cloudand_password = "******" cloudant_account = "5d99de7b-6366-4dce-829c-1055baad93e6-bluemix" db_name = "user-db" client = cloudant.Cloudant(cloudant_api_key, cloudand_password, account=cloudant_account, connect=True, auto_renew=True) db = client[db_name] #Determine usage id = role+':'+username if id in db: doc = db[id] #Recalculate hashed password salt = doc['salt'] hashed_password = hashlib.sha512(str(password + salt).encode('utf-8')).hexdigest() if hashed_password == doc['hashed_password']: role = doc['role'] success = True message = 'Successfully logged in as user: '******' with role: '+role+'.' else: success = False message = 'Failed to login. Password incorrect.' else: success = False message = 'Failed to login. Username with that role not found.' client.disconnect() return success, message
def main(): config.configure_logging('analyze.log') # Load top 25 from file with open(config.top_20_save_file, 'r') as f: freader = csv.reader(f) top_20 = [(row[0], row[1]) for row in freader] # Authorize tweepy with open(config.tweepy_credentials_file, 'r') as f: creds = json.load(f) auth = OAuthHandler(creds['consumerKey'], creds['consumerSecret']) auth.set_access_token(creds['accessToken'], creds['accessTokenSecret']) api = tweepy.API(auth) # Instantiate analyzer analyzer = SentimentIntensityAnalyzer() # Connect to database with open(config.cloudant_credentials_File, 'r') as f: creds = json.load(f) conn = cloudant.Cloudant(creds['username'], creds['password'], url='https://' + creds['host'], connect=True) db = conn['sentiments'] total = 0 for coin in top_20: symb = coin[0] name = coin[1] # search for and analyze tweets regarding current currency tweets = search_and_analyze(api, analyzer, symb, name) for t in tweets: logging.info('Adding record: %s...', str(t)) data = {'datetime': t[0], 'symbol': t[1], 'sentiment': t[2]} # dont exceed rate limit if (total + 1) % 10 == 0: time.sleep(1) tweet_doc = db.create_document(data) dt = datetime.utcnow() if tweet_doc.exists(): logging.info('SUCCESS.') else: logging.error('FAILED.') total += 1 logging.info('Total records inserted: %d', total)
def main(payload): api_key = 'ciestruitypherrdrictions' password = '******' account = 'cef81edb-8e36-4aa5-a9e5-9c0c606b1483-bluemix' dbu = ibm_db.connect( "DATABASE=BLUDB;HOSTNAME=dashdb-txn-flex-yp-dal09-172.services.dal.bluemix.net;PORT=50000;PROTOCOL=TCPIP;UID=bluadmin;PWD=Njc5YmYxZTRlZGM4;", "", "") #Connection Test - Sample client = cloudant.Cloudant(api_key, password, account=account, connect=True, auto_renew=True) db = client['machine_data'] result = 1 # Pull last entry from Cloudant sample_query = cloudant.query.Query(db, selector={'time': {'$gt': 0}}) for doc in sample_query(limit=1)['docs']: SQL = "INSERT INTO PAPER_DATA.SENSOR_DATA (TIME, SENSOR_ID, VALUE) VALUES (?, ?, ?);" stmt = ibm_db.prepare(dbu, SQL) ibm_db.bind_param(stmt, 1, doc["time"]) ibm_db.bind_param(stmt, 2, doc["id"]) if doc["id"] == "ductTemp": ibm_db.bind_param(stmt, 3, doc["temp"]) elif doc["id"] == "ductHumidity": ibm_db.bind_param(stmt, 3, doc["humidity"]) elif doc["id"] == "simTemp": ibm_db.bind_param(stmt, 3, doc["temp"]) elif doc["id"] == "ambientHumidity": ibm_db.bind_param(stmt, 3, doc["humidity"]) elif doc["id"] == "ambientTemp": ibm_db.bind_param(stmt, 3, doc["temp"]) ibm_db.execute(stmt) client.disconnect() return result
def main(): """ Driver function """ config.configure_logging('prepare.log') logging.info('Beginning preparation of databases.') # connect to server try: logging.info('Connecting to Cloudant server...') with open(config.cloudant_credentials_File, 'r') as f: creds = json.load(f) conn = cloudant.Cloudant(creds['username'], creds['password'], url='https://' + creds['host'], connect=True) except Exception: # connection failure logging.exception('Error connecting to Cloudant server.') sys.exit('Exiting.') logging.info('Finished connecting to Cloudant server.') # create summaries db if it doesnt exist if not check_db(conn, 'summaries'): create_db_summaries(conn) # if sentiments db exists, summarize its data, then delete if check_db(conn, 'sentiments'): summary.create_summaries(conn) logging.info('Deleting database "sentiments"...') conn.delete_database('sentiments') logging.info('Finished deleting database.') create_db_sentiments(conn) # Update top 20 file top_20.get_top_20() logging.info('Finished preparation of databases.') logging.info('Ready for sentiment records.')
def __init_app__(self, app): """ Initializes the connection using the settings from `config.py`. """ cloudant_user = app.config.get('CLOUDANT_USER') cloudant_pwd = app.config.get('CLOUDANT_PWD') cloudant_account = app.config.get('CLOUDANT_ACCOUNT', cloudant_user) cloudant_database = app.config.get('CLOUDANT_DB') try: FlaskCloudant.CLIENT = cloudant.Cloudant(cloudant_user, cloudant_pwd, account=cloudant_account) self.__connect__() self._db = FlaskCloudant.CLIENT[cloudant_database] self.__disconnect__() except CloudantClientException as ex: raise FlaskCloudantException(ex.status_code) except HTTPError as ex: raise FlaskCloudantException(ex.response.status_code, cloudant_user) except KeyError: raise FlaskCloudantException(400, cloudant_database)
# See the License for the specific language governing permissions and # limitations under the License. # More stuff #Reference: # http://python-cloudant.readthedocs.org/en/latest/getting_started.html # https://github.com/IBM-Bluemix/bluemix-python-flask-sample import os.path, time from flask import Flask, request, render_template, send_file import datetime import cloudant import hashlib app = Flask(__name__) client = cloudant.Cloudant('', '', url='https:/') # or using url # client = Cloudant(USERNAME, PASSWORD, url='https://acct.cloudant.com') # Connect to the account client.connect() # Open an existing database my_database = client['my_database'] @app.route('/') def Welcome(): #return app.send_static_file('index.html') return render_template('index.html')
import os import cloudant from flask import Flask, render_template, request import random from watson_developer_cloud import AlchemyLanguageV1 app = Flask(__name__) username = os.environ['DB_USERNAME'] password = os.environ['DB_PASSWORD'] host = os.environ.get('DB_HOST', '{username}.cloudant.com'.format(username=username)) url = "https://{username}:{password}@{host}".format(username=username, password=password, host=host) client = cloudant.Cloudant(username, password, account=username, url=url) client.connect() db = client['ibase'] alchemy_key = os.environ.get('ALCHEMY_KEY', '') apples = [{ 'price': random.randint(10, 25), **doc } for doc in db if doc.get('type', '') == 'apple'] @app.route('/') def index(): return render_template('index.html', apples=apples)
def main(payload): #Parse payload username, password = str(payload['body'].get('username')), str( payload['body'].get('password')) usage, role = str(payload['body'].get('usage')), str( payload['body'].get('role')) success = False message = '' #Verify payload if username == "None" or password == "None" or usage == "None" or role == "None": #(usage == 'create_account' and role == None): success = False message = 'Payload is not valid. One of username, password, usage, or role is missing.' else: #Calculate hashed password salt = uuid.uuid4().hex hashed_password = hashlib.sha512( str(password + salt).encode('utf-8')).hexdigest() #Begin accessing the database cloudant_api_key = "bsideentsamedgediabsidst" cloudand_password = "******" cloudant_account = "5d99de7b-6366-4dce-829c-1055baad93e6-bluemix" db_name = "user-db" client = cloudant.Cloudant(cloudant_api_key, cloudand_password, account=cloudant_account, connect=True, auto_renew=True) db = client[db_name] #Determine usage id = role + ':' + username if usage == 'create_account': if id in db: success = False message = 'Failed to create user. Username already exists.' else: doc = db.create_document({ '_id': id, 'username': username, 'hashed_password': hashed_password, 'salt': salt, 'role': role, }) success = True message = 'Successfully create user: "******".' elif usage == 'login': if id in db: doc = db[id] #Recalculate hashed password salt = doc['salt'] hashed_password = hashlib.sha512( str(password + salt).encode('utf-8')).hexdigest() if hashed_password == doc['hashed_password']: role = doc['role'] success = True message = 'Successfully logged in as user: '******' with role: ' + role + '.' else: success = False message = 'Failed to login. Password incorrect.' else: success = False message = 'Failed to login. Username with that role not found.' else: success = False message = 'Usage is not valid. Expected: login or create_account' client.disconnect() return {"body": {"success": success, "message": message, "role": role}}