Example #1
0
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 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
Example #3
0
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()
Example #4
0
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()
Example #5
0
from cloudant import Cloudant
import os, json
from pathlib import Path

g=Path("inventory","vcap-local.json")
with open(g) 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)

client.connect()
db = client["bolts-parts"]
def getpart():
    pass
selector={"_id":{"$gt":{}}}
result = db.get_query_result(selector, fields=["part","description","quantity"])

for doc in result:
    print(doc)


client.disconnect()
Example #6
0
class db:
    dataLabel = "data"
    timeLabel = "stamp"
    statusLabel = "state"
    lastUpdateLabel = 'lastUpdate'
    commandLabel = "command"

    def __init__(self):
        if 'VCAP_SERVICES' in os.environ:
            vcap = json.loads(os.getenv('VCAP_SERVICES'))
            print('Found VCAP_SERVICES')
            if 'cloudantNoSQLDB' in vcap:
                self.creds = vcap['cloudantNoSQLDB'][0]['credentials']
                self.user = self.creds['username']
                self.password = self.creds['password']
        elif os.path.isfile('vcap-local.json'):
            with open('vcap-local.json') as f:
                vcap = json.load(f)
                print('Found local VCAP_SERVICES')
                self.creds = vcap['services']['cloudantNoSQLDB'][0][
                    'credentials']
                self.user = self.creds['username']
                self.password = self.creds['password']

    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 createNewDevice(self):
        doc = self.db.create_document({self.dataLabel: []})
        doc[self.lastUpdateLabel] = str(datetime.datetime.now())
        doc[self.commandLabel] = []
        doc[constant.hour_frequency] = []
        doc.save()
        return doc["_id"]

    def addData(self, id, state, time=datetime.datetime.now()):
        doc = self.db[id]
        Document.list_field_append(doc, self.dataLabel, {
            self.timeLabel: str(time),
            self.statusLabel: state
        })
        doc[self.lastUpdateLabel] = str(time)
        doc.save()

    """
    dataArray is an array of tuple
    each tuple has in fist position the data and in second position the timestamp
    """

    def addDataArray(self, id, dataArray):
        doc = self.db[id]
        for i in dataArray:
            Document.list_field_append(doc, self.dataLabel, {
                self.timeLabel: str(i[1]),
                self.statusLabel: i[0]
            })

        doc[self.lastUpdateLabel] = str(datetime.datetime.now())
        doc.save()

    def clearDatabase(self):
        self.client.delete_database(self.dbName)
        self.db = None

    def disconnect(self):
        self.client.disconnect()
        self.client = None
        self.db = None

    def getDataFromId(self, id):
        doc = self.db[id]

        return (doc[self.dataLabel], doc[constant.hour_frequency])

    def getDeviceList(self):
        return self.db.keys(remote=True)

    def resetConnection(self):
        self.disconnect()
        self.connect()

    def getIdLastUpdate(self, id):
        doc = self.db[id]
        return doc[self.lastUpdateLabel]

    def addCommand(self, id, command):
        doc = self.db[id]
        doc[self.commandLabel].append(command)
        doc.save()

    def getCommandList(self, id):
        doc = self.db[id]
        return doc[self.commandLabel]

    def deleteCommands(self, id):
        doc = self.db[id]
        doc[self.commandLabel] = []
        doc.save()

    def computeOccupancy(self, measurementFrequency, numGraphLabels,
                         computedHours, deviceID):
        doc = self.db[deviceID]
        dataToCompute = doc[constant.dataLabel]
        numEntriesToCompute = (constant.minutesInHour //
                               measurementFrequency) * computedHours
        lenPerLabel = numEntriesToCompute // numGraphLabels
        print(numEntriesToCompute)
        dataToCompute = dataToCompute[-numEntriesToCompute:]
        frequencyPerLabel = []

        def chunks(arr, n):
            for i in range(0, len(arr), n):
                yield arr[i:i + n]

        dataPerLabel = list(chunks(dataToCompute, lenPerLabel))
        print(dataPerLabel)

        for label in range(numGraphLabels):
            frequencyPerLabel.append(0)
            for el in dataPerLabel[label]:
                if el[constant.db_entry_state_label]:
                    frequencyPerLabel[label] += 1
        hours = doc[constant.hour_frequency] + frequencyPerLabel
        doc[constant.hour_frequency] = hours
        doc.save()