Esempio n. 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
Esempio n. 2
0
 def __init__(self):
     mimetypes.init()
     cloudant_user = os.environ["CLOUDANT_USER"]
     cloudant_pass = os.environ["CLOUDANT_PASS"]
     client = Cloudant(cloudant_user, cloudant_pass, account=cloudant_user)
     client.connect()
     session = client.session()
     self.database = client['scout']
     self.client = client
Esempio n. 3
0
def connect_db():
    USERNAME, PASSWORD, URL, DATABASE_NAME = connect_filedb.getconfig()
    client = Cloudant(USERNAME, PASSWORD, url=URL)
    client.connect()
    session = client.session()
    if DATABASE_NAME in client.all_dbs():
        return DATABASE_NAME, client
    else:
        return "No such Database exist"
    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
Esempio n. 5
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()
Esempio n. 6
0
from flask import render_template, request, Blueprint, flash, redirect, url_for, abort, Response
from inventory.main.forms import NewPartForm, NavForm, EditPartForm, LocationForm
main = Blueprint('main', __name__)
g = Path("inventory/main", "vcap-local.json")
client = None

with open(g.absolute()) 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.connect()
partsdb = client["bolts-parts"]
locationdb = client["bolts-locations"]


def update():
    partsdb = client["bolts-parts"]
    locationdb = client["bolts-locations"]


@main.route("/")
@main.route("/index")
def home():
    x = len(partsdb)
    return render_template('index2.html', title="Bolts Inventory", x=x)
Esempio n. 7
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