Example #1
0
class DBConnection(object):

    def __init__(self):
        #mongodb_uri = "mongodb://13.76.244.22:27017"
        #mongolab_uri = "mongodb://*****:*****@ds062818.mlab.com:62818/MongoLab-25"
        #connectionString = 'mongodb://*****:*****@ds062818.mlab.com:62818/MongoLab-25'
        #self.client = MongoClient(mongolab_uri,
        #             connectTimeoutMS=30000,
        #             socketTimeoutMS=None,
        #             socketKeepAlive=True)
        #self.db = self.client.get_default_database()
        #self.con = Connection(mongodb_uri)
        self.con = Connection()

        self.con.register([Route])
        self.con.register([Stop])

        self.routes = self.con.Route
        self.stops = self.con.Stop
        
    def __del__(self):
        self.con.close()
        self.con.disconnect()

    def connect():        
        con = Connection()
        routes = con.amdoraft.routes
        stops = con.amdoraft.stops
        return

    def disconnect():
        return
Example #2
0
class MongoFest(BaseDB):
	def __init__(self,app):
		self.conn = Connection(app.config['MONGODB_HOST'],app.config['MONGODB_PORT'])	
		self.conn.register(Host)
		self.logger = app.logger
	def find(self,hostname='',tags=''):
		if hostname == '':
			return [ self._clean_oid(h) for h in self.conn.sysfest.Host.find().sort("hostname", pymongo.ASCENDING) ]
		elif hostname != '':
			regx = re.compile(hostname)
			return [ self._clean_oid(h) for h in self.conn.sysfest.Host.find({"$or":[{'hostname':regx},{'homes.hostnames.val':regx}]}).sort("hostname", pymongo.ASCENDING) ]
	def search(self,query):
		tag_pattern = re.compile('tag:(\w+)')
		host_pattern = re.compile('host:([\w\.-]+)')
		tags = tag_pattern.findall(query)
		hosts = host_pattern.findall(query)
		query = tag_pattern.sub('',query)
		query = host_pattern.sub('',query)
		key_words = query.split(' ')

		terms = [ {"description":re.compile(x,flags=re.I)} for x in key_words]

		if hosts:
			terms = terms + [{"$or":[{'hostname':re.compile(x)},{'homes.hostnames.val':re.compile(x)}]} for x in hosts]
		
		if tags: #pythonic (moronic) way to check if an array is empty
			terms = terms + [{"tags":{"$all":tags}}]

		return [ self._clean_oid(h) for h in self.conn.sysfest.Host.find({"$and":terms}).sort("hostname", pymongo.ASCENDING) ]

	def find_one(self,host_id):
		if isinstance(host_id, basestring):
			host_id=bson.objectid.ObjectId(host_id)
		host = self._clean_oid(self.conn.sysfest.Host.find_one({'_id':host_id}))
		return host
	def update(self,host_id,values):
		self.conn.sysfest.hosts.update({"_id":bson.objectid.ObjectId(host_id)},{"$set":values})
		return self.find_one(host_id)
	def create(self,values):
		oid = self.conn.sysfest.hosts.insert(values)
		return self.find_one(host_id=oid)
	def delete(self,host_id):
		return self.conn.sysfest.hosts.remove({'_id':bson.objectid.ObjectId(host_id)})

	def close(self):
		self.conn.disconnect()

	def _clean_oid(self,host):
		if host is not None and isinstance(host["_id"], bson.objectid.ObjectId):
			host["_id"]=str(host["_id"])
		return host
Example #3
0
class DBConnection(object):

    def __init__(self):
        #mongodb_uri = "mongodb://13.76.244.22:27017"
        #mongolab_uri = "mongodb://*****:*****@ds062818.mlab.com:62818/MongoLab-25"
        connectionString = 'insert mongodb uri here'
        #self.client = MongoClient(mongolab_uri,
        #             connectTimeoutMS=30000,
        #             socketTimeoutMS=None,
        #             socketKeepAlive=True)
        #self.db = self.client.get_default_database()
        #self.con = Connection(mongodb_uri)
        self.con = Connection()

        self.con.register([Project])
        self.con.register([Files])
        self.con.register([Job])
        self.con.register([User])
        self.con.register([Admin])
        self.con.register([Log])
        self.con.register([Server])

        self.projects = self.con.Project
        self.files = self.con.Files
        self.jobs = self.con.Job
        self.users = self.con.User
        self.admins = self.con.Admin
        self.logs = self.con.Log
        self.server = self.con.Server

    def __del__(self):
        self.con.close()
        self.con.disconnect()

    def connect():        
        con = Connection()
        projects = con.vcad.projects
        admins = con.vcad.admin
        con.register([Project])
        return

    def disconnect():
        return
Example #4
0
class DBConnection(object):
    def __init__(self):
        #mongodb_uri = "mongodb://13.76.244.22:27017"
        #mongolab_uri = "mongodb://*****:*****@ds062818.mlab.com:62818/MongoLab-25"
        connectionString = 'insert mongodb uri here'
        #self.client = MongoClient(mongolab_uri,
        #             connectTimeoutMS=30000,
        #             socketTimeoutMS=None,
        #             socketKeepAlive=True)
        #self.db = self.client.get_default_database()
        #self.con = Connection(mongodb_uri)
        self.con = Connection()

        self.con.register([Project])
        self.con.register([Files])
        self.con.register([Job])
        self.con.register([User])
        self.con.register([Admin])
        self.con.register([Log])
        self.con.register([Server])

        self.projects = self.con.Project
        self.files = self.con.Files
        self.jobs = self.con.Job
        self.users = self.con.User
        self.admins = self.con.Admin
        self.logs = self.con.Log
        self.server = self.con.Server

    def __del__(self):
        self.con.close()
        self.con.disconnect()

    def connect():
        con = Connection()
        projects = con.vcad.projects
        admins = con.vcad.admin
        con.register([Project])
        return

    def disconnect():
        return
class MongoKit(object):
    """This class is used to integrate `MongoKit`_ into a Flask application.

    :param app: The Flask application will be bound to this MongoKit instance.
                If an app is not provided at initialization time than it
                must be provided later by calling :meth:`init_app` manually.

    .. _MongoKit: http://namlook.github.com/mongokit/
    """

    def __init__(self, app=None, database=None):
        #: :class:`list` of :class:`mongokit.Document`
        #: which will be automated registed at connection
        self.registered_documents = []
        self.mongokit_connection = None
        self.database = database

        if app is not None:
            self.app = app
            self.init_app(self.app)
        else:
            self.app = None

    def init_app(self, app):
        """Also it registers the
        :class:`flask.ext.mongokit.BSONObjectIdConverter`
        as a converter with the key word **ObjectId**.

        :param app: The Flask application will be bound to this MongoKit
                    instance.
        """
        app.config.setdefault('MONGODB_HOST', '127.0.0.1')
        app.config.setdefault('MONGODB_PORT', 27017)
        app.config.setdefault('MONGODB_DATABASE', 'flask')
        app.config.setdefault('MONGODB_SLAVE_OKAY', False)
        app.config.setdefault('MONGODB_USERNAME', None)
        app.config.setdefault('MONGODB_PASSWORD', None)
        app.config.setdefault('MONGODB_MAX_POOL_SIZE', 10)

        # register extension with app
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['mongokit'] = self

        app.url_map.converters['ObjectId'] = BSONObjectIdConverter

        self.app = app

    def register(self, documents):
        """Register one or more :class:`mongokit.Document` instances to the
        connection.

        Can be also used as a decorator on documents:

        .. code-block:: python

            db = MongoKit(app)

            @db.register
            class Task(Document):
                structure = {
                   'title': unicode,
                   'text': unicode,
                   'creation': datetime,
                }

        :param documents: A :class:`list` of :class:`mongokit.Document`.
        """

        #enable decorator usage as in mongokit.Connection
        decorator = None
        if not isinstance(documents, (list, tuple, set, frozenset)):
            # we assume that the user used this as a decorator
            # using @register syntax or using db.register(SomeDoc)
            # we stock the class object in order to return it later
            decorator = documents
            documents = [documents]

        for document in documents:
            if document not in self.registered_documents:
                self.registered_documents.append(document)

        if decorator is None:
            return self.registered_documents
        else:
            return decorator

    def connect(self):
        """Connect to the MongoDB server and register the documents from
        :attr:`registered_documents`. If you set ``MONGODB_USERNAME`` and
        ``MONGODB_PASSWORD`` then you will be authenticated at the
        ``MONGODB_DATABASE``.
        """
        self.mongokit_connection = Connection(
            host=self.app.config.get('MONGODB_HOST'),
            port=self.app.config.get('MONGODB_PORT'),
            max_pool_size=self.app.config.get('MONGODB_MAX_POOL_SIZE'),
            slave_okay=self.app.config.get('MONGODB_SLAVE_OKAY')
        )
        self.mongokit_connection.register(self.registered_documents)
        if self.database:
            self.mongokit_db = Database(self.mongokit_connection, self.database)
        else:
            self.mongokit_db = Database(self.mongokit_connection, self.app.config.get('MONGODB_DATABASE'))
        if self.app.config.get('MONGODB_USERNAME') is not None:
            self.mongokit_db.authenticate(
                self.app.config.get('MONGODB_USERNAME'),
                self.app.config.get('MONGODB_PASSWORD')
            )

    @property
    def connected(self):
        """Connection status to your MongoDB."""
        return self.mongokit_connection is not None

    def disconnect(self):
        """Close the connection to your MongoDB."""
        if self.connected:
            self.mongokit_connection.disconnect()
            self.mongokit_connection = None
            del self.mongokit_db

    def __getattr__(self, name, **kwargs):
        if not self.connected:
            self.connect()
        return getattr(self.mongokit_db, name)