Esempio n. 1
0
class ServerTestCase(unittest.TestCase):
    def setUp(self):
        self.couchdb = CouchdbResource()
        
    def tearDown(self):
        self.couchdb = None
        try:
            self.server.delete_db('simplecouchdb_test')
        except:
            pass

    def testGetInfo(self):
        info = self.couchdb.get()
        self.assert_(info.has_key('version'))
        
    def testCreateDb(self):
        res = self.couchdb.put('/simplecouchdb_test/')
        self.assert_(res['ok'] == True)
        all_dbs = self.couchdb.get('/_all_dbs')
        self.assert_('simplecouchdb_test' in all_dbs)
        self.couchdb.delete('/simplecouchdb_test/')

    def testCreateEmptyDoc(self):
        res = self.couchdb.put('/simplecouchdb_test/')
        self.assert_(res['ok'] == True)
        res = self.couchdb.post('/simplecouchdb_test/', payload={})
        self.couchdb.delete('/simplecouchdb_test/')
        self.assert_(len(res) > 0)

    def testRequestFailed(self):
        bad = CouchdbResource('http://localhost:10000')
        self.assertRaises(RequestFailed, bad.get)
Esempio n. 2
0
    def __init__(self, databases):
        """ initialize couchdbkit handler with COUCHDB_DATABASES
        settings """

        self.__dict__ = self.__shared_state__

        # create databases sessions
        for app_name, uri in databases:

            try:
                if isinstance(uri, tuple):
                    # case when you want to specify server uri 
                    # and database name specifically. usefull
                    # when you proxy couchdb on some path 
                    server_uri, dbname = uri
                else:
                    server_uri, dbname = uri.rsplit("/", 1)
            except ValueError:
                raise ValueError("couchdb uri [%s:%s] invalid" % (
                    app_name, uri))

                
            res = CouchdbResource(server_uri, timeout=COUCHDB_TIMEOUT)

            server = Server(server_uri, resource_instance=res)
            app_label = app_name.split('.')[-1]
            self._databases[app_label] = (server, dbname)
Esempio n. 3
0
 def __authenticate(self):
     user, passwd = config.couchdb.user, config.couchdb.password
     if (all((user, passwd))):
         auth = restkit.BasicAuth(user, passwd)
         self.__auth_resource = CouchdbResource(filters=[auth])
     else:
         self.__auth_resource = None
Esempio n. 4
0
def main(db_name, db_user, db_pass, db_host, sequence_file, zone_dir, **tls_args):
    # Starting Sequence for change stream
    sequence = sequence_read(sequence_file)
    click.echo('Skipping %s changes.' % sequence)
    # CouchDB Connection
    tls_args['cert_reqs'] = ssl.CERT_REQUIRED
    tls_args['ssl_version'] = ssl.PROTOCOL_TLSv1_2
    auth = CouchdbResource(filters=[BasicAuth(db_user, db_pass)], **tls_args)
    server = Server(uri=db_host, resource_instance=auth)
    db = server[db_name]

    if sequence == 0:
        click.echo('Fast track syncing all zones...')
        c = Consumer(db)
        result = c.fetch(descending=True, limit=1)
        # Fast track to this sequence
        sequence = result['last_seq']
        # Go get all the current zones.
        zones = c.fetch()
        for zone in zones['results']:
            domain = zone['id']
            try:
                doc = db.get(docid=domain)
            except ResourceNotFound, e:
                click.echo('%s not found (this is normal if the zone was deleted)' % domain)
            else:
                zone_update(domain, doc['data'], zone_dir)
        sequence_write(sequence_file, sequence)  # Keep track of our sync point
        click.echo('Fast track syncing done')
Esempio n. 5
0
 def sync_all_app(self, uri, dbname, views):
     '''
     Create a database session for each databases, then start the syncing
     process.
     Databases are described by tuples containing the application name and
     the database URL in which views must be synchronized.
     @param uri: Uri of the couchdb server
     @param dbname: Database name
     @param views: Name of the views
     '''
     for view in views:
         res = CouchdbResource(uri, timeout=COUCHDB_TIMEOUT)
         server = Server(uri, resource_instance=res)
         self.sync(server, dbname, view, views[view])
Esempio n. 6
0
    def __init__(self, uri='http://127.0.0.1:5984', uuid_batch_count=DEFAULT_UUID_BATCH_COUNT, 
            transport=None):
        """ constructor for Server object
        
        @param uri: uri of CouchDb host
        @param uuid_batch_count: max of uuids to get in one time
        @param transport: an transport instance from :mod:`restclient.transport`. Can be used
                to manage authentification to your server or proxy.
        """
        
        if not uri or uri is None:
            raise ValueError("Server uri is missing")

        self.uri = uri
        self.transport = transport
        self.uuid_batch_count = uuid_batch_count
        self._uuid_batch_count = uuid_batch_count
        
        self.res = CouchdbResource(uri, transport=transport)
        self.uuids = []
Esempio n. 7
0
    def __init__(self, databases):
        """ initialize couchdbkit handler with COUCHDB_DATABASES
        settings """

        self.__dict__ = self.__shared_state__

        # Convert old style to new style
        if isinstance(databases, (list, tuple)):
            databases = dict((app_name, {
                'URL': uri
            }) for app_name, uri in databases)

        # create databases sessions
        for app_name, app_setting in databases.items():
            uri = app_setting['URL']

            # Do not send credentials when they are both None as admin party will give a 401
            user = app_setting.get('USER')
            password = app_setting.get('PASSWORD')
            filters = [BasicAuth(user, password)
                       ] if (user or password) is not None else []

            try:
                if isinstance(uri, (list, tuple)):
                    # case when you want to specify server uri
                    # and database name specifically. usefull
                    # when you proxy couchdb on some path
                    server_uri, dbname = uri
                else:
                    server_uri, dbname = uri.rsplit("/", 1)
            except ValueError:
                raise ValueError("couchdb uri [%s:%s] invalid" %
                                 (app_name, uri))

            res = CouchdbResource(server_uri,
                                  timeout=COUCHDB_TIMEOUT,
                                  filters=filters)

            server = Server(server_uri, resource_instance=res)
            app_label = app_name.split('.')[-1]
            self._databases[app_label] = (server, dbname)
Esempio n. 8
0
 def testRequestFailed(self):
     bad = CouchdbResource('http://localhost:10000')
     self.assertRaises(RequestError, bad.get)
Esempio n. 9
0
 def setUp(self):
     self.couchdb = CouchdbResource()
     try:
         self.couchdb.delete('/couchdkbit_test')
     except:
         pass
Esempio n. 10
0
class ServerTestCase(unittest.TestCase):
    def setUp(self):
        self.couchdb = CouchdbResource()
        try:
            self.couchdb.delete('/couchdkbit_test')
        except:
            pass

    def tearDown(self):
        self.couchdb = None
        try:
            self.couchdb.delete('/couchdkbit_test')
        except:
            pass

    def testGetInfo(self):
        info = self.couchdb.get().json_body
        self.assert_(info.has_key('version'))

    def testCreateDb(self):
        res = self.couchdb.put('/couchdkbit_test').json_body
        self.assert_(res['ok'] == True)
        all_dbs = self.couchdb.get('/_all_dbs').json_body
        self.assert_('couchdkbit_test' in all_dbs)
        self.couchdb.delete('/couchdkbit_test')

    def testCreateEmptyDoc(self):
        res = self.couchdb.put('/couchdkbit_test/').json_body
        self.assert_(res['ok'] == True)
        res = self.couchdb.post('/couchdkbit_test/', payload={}).json_body
        self.couchdb.delete('/couchdkbit_test')
        self.assert_(len(res) > 0)

    def testRequestFailed(self):
        bad = CouchdbResource('http://localhost:10000')
        self.assertRaises(RequestError, bad.get)
Esempio n. 11
0
 def setUp(self):
     self.couchdb = CouchdbResource()
     try:
         self.couchdb.delete('/couchdkbit_test')
     except:
         pass
Esempio n. 12
0
 def setUp(self):
     self.couchdb = CouchdbResource()
Esempio n. 13
0
class Server(object):
    """ Server object that allows you to access and manage a couchdb node. 
    A Server object can be used like any `dict` object.
    """
    
    def __init__(self, uri='http://127.0.0.1:5984', uuid_batch_count=DEFAULT_UUID_BATCH_COUNT, 
            transport=None):
        """ constructor for Server object
        
        @param uri: uri of CouchDb host
        @param uuid_batch_count: max of uuids to get in one time
        @param transport: an transport instance from :mod:`restclient.transport`. Can be used
                to manage authentification to your server or proxy.
        """
        
        if not uri or uri is None:
            raise ValueError("Server uri is missing")

        self.uri = uri
        self.transport = transport
        self.uuid_batch_count = uuid_batch_count
        self._uuid_batch_count = uuid_batch_count
        
        self.res = CouchdbResource(uri, transport=transport)
        self.uuids = []
        
    def info(self):
        """ info of server 
        @return: dict
        """
        return self.res.get()
    
    def all_dbs(self):
        """ get list of databases in CouchDb host """
        result = self.res.get('/_all_dbs')
        return result
        
    def create_db(self, dbname):
        """ Create a database on CouchDb host

        @param dname: str, name of db

        @return: Database instance if it's ok or dict message
        """
        _dbname = url_quote(validate_dbname(dbname), safe=":")
        res = self.res.put('/%s/' % _dbname)
        if res['ok']:
            return Database(self, dbname)
        return res['ok']

    def get_or_create_db(self, dbname):
        """
        Try to return a Database object for dbname. If 
        database doest't exist, it will be created.
        
        """
        try:
            return self[dbname]
        except ResourceNotFound:
            return self.create_db(dbname)
        
    def delete_db(self, dbname):
        """
        Delete database
        """
        del self[dbname]
        
    def next_uuid(self, count=None):
        """
        return an available uuid from couchdbkit
        """
        if count is not None:
            self._uuid_batch_count = count
        else:
            self._uuid_batch_count = self.uuid_batch_count
        
        self.uuids = self.uuids or []
        if not self.uuids:
            self.uuids = self.res.get('/_uuids', count=self._uuid_batch_count)["uuids"]
        return self.uuids.pop()
          
    def __getitem__(self, dbname):
        if dbname in self:
            return Database(self, dbname)
        raise ResourceNotFound
        
    def __delitem__(self, dbname):
        return self.res.delete('/%s/' % url_quote(dbname, safe=":"))
        
    def __contains__(self, dbname):
        if dbname in self.all_dbs():
            return True
        return False
        
    def __iter__(self):
        for dbname in self.all_dbs():
            yield Database(self, dbname)

    def __len__(self):
        return len(self.all_dbs())
        
    def __nonzero__(self):
        return (len(self) > 0)