Exemple #1
0
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
Exemple #2
0
class MarketDB:
    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)

    def fetch_client(self):
        return self.client

    def fetch_db(self):
        return self.db
Exemple #3
0
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
Exemple #4
0
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)
Exemple #5
0
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
Exemple #6
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()
Exemple #7
0
    GEOCODING_APIKEY = os.getenv('GEOCODING_APIKEY')
    DB_NAME = os.getenv('DB_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)
        db = client.create_database(DB_NAME, throw_on_exists=False)
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)

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)
        # using line-simulator
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN, "http://localhost:8080")
AREA_COUNT = {
Exemple #8
0
parking_db_name = 'parking_tw'
client = None
db = None
population_db = None
parking_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)
        population_db = client.create_database(population_db_name,
                                               throw_on_exists=False)
        parking_db = client.create_database(parking_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)
    population_db = client.create_database(population_db_name,
                                           throw_on_exists=False)
    parking_db = client.create_database(parking_db_name, throw_on_exists=False)
elif os.path.isfile('vcap-local.json'):
    with open('vcap-local.json') as f:
Exemple #9
0
stats_db_name = 'statsdbohiodev'

client = None
statsdb = 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)
        statsdb = client.create_database(stats_db_name, throw_on_exists=False)
elif os.path.isfile('D:/dash/vcap-local.json'):
    with open('D:/dash/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)
        statsdb = client.create_database(stats_db_name, throw_on_exists=False)
else:
    print('error')


def get_stats():
Exemple #10
0
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()
if client is not None:
Exemple #11
0
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
Exemple #12
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()
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:
        client.disconnect()
Exemple #14
0
db_location_name = 'location'
client = None
db = None

port = int(os.getenv('PORT', 8000))

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_user = client.create_database(db_user_name, throw_on_exists=False)
        db_location = client.create_database(db_location_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_user = client.create_database(db_user_name, throw_on_exists=False)
        db_location = client.create_database(db_location_name, throw_on_exists=False)

@app.route('/rumr/api/users', methods=['GET'])
def get_users():
Exemple #15
0
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 8000
port = int(os.getenv('PORT', 8000))
Exemple #16
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()
Exemple #17
0
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)

# On IBM Cloud Cloud Foundry, get the port number from the environment variable PORT
Exemple #18
0
def main(argv=None):  # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by Bernard Gautier on %s.
  Copyright 2018 Ochrin. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license,
                                formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument("-m", "--mac", help="mac address of device")
        parser.add_argument("-t", "--token", help="token of device")

        # Process arguments
        args = parser.parse_args()

        mac = args.mac
        token = args.token

        print("Connecting to database...")
        db_name = 'air-device-db'
        client = None
        db = None
        mydir = os.path.dirname(os.path.realpath(__file__))

        if os.path.isfile(os.path.join(mydir, 'vcap-local.json')):
            with open(os.path.join(mydir, 'vcap-local.json')) as f:
                vcap = json.load(f)
                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("DB not found or created")
            print("%s", os.getcwd())
            print("%s", os.path.dirname(os.path.realpath(__file__)))
            return -1

        print("Connected.")

        if mac in db:
            print("Device already in db")
            print("END.")
            return 0

        print("Adding device with mac address = ", mac, " and token = ", token)

        data = {
            '_id': mac,
            'token': token,
            'owner_email': '',
            'date_reg': '',
            'place': ''
        }
        if client:
            my_document = db.create_document(data)
            if my_document.exists():
                print("Device added")
                print("END.")

        return 0
    except KeyboardInterrupt:
        ### handle keyboard interrupt ###
        return 0