How-to write Python for Cassandra

First of all, you need to install the Python driver for Cassandra module, pycassa. The easiest way is to use pip or easy_install to install it.

$ pip install pycassa
or
$ easy_install pycassa

Then, you can start to write scripts. Here is an example:

#!/usr/bin/python
'''
Create a user
'''
import pycassa
from pycassa.system_manager import SystemManager

    def __do_create_cassandrauser(self):
        isSuccess = False
        
        cassandra_user = self.newuser
        cassandra_pass = self.newuser
        cassandra_db = self.newuser
        cred = None
        if(self.sysuser is not None and self.syspass is not None) :
            cred = {'username' : self.sysuser, 'password' : self.syspass}          
        
        try:
            #connect to cassandra

            '''
                before connect, modify the connect string as:
                "['vip:port','vip2:port'...]" so that this can be used in server list
                the vip str should be like "vip1,vip2,vip3",
                and we regard all port are the same.
                SystemManager.server didn't support a array of server list now, only ConnectionPool.server_list support
                So I will go through the vip list and connect to an available host
            '''
            vip_list = self.vip.split(',')            
            for myvip in vip_list:
                try:
                    cons = myvip + ':' + str(self.port)
                    sm = SystemManager(server=cons, credentials=cred)
                    break
                except: 
                    pass
            
            #c = ConnectionPool(keyspace='system', server_list=con, credentials=cred)
                        
            #check if user exist: by check if database name exist(database name and username are the same) 
            database_names = sm.list_keyspaces()
            if cassandra_db in database_names:
                raise DbUserCreateError('DbUserCreateError: In Remote Oracle DB User [' + 
                                        cassandra_user + '] Already Exists.')

            sm.create_keyspace(cassandra_db, pycassa.system_manager.NETWORK_TOPOLOGY_STRATEGY, {'DC1': '1', 'DC2': '1'})
        
        except Exception as e:            
            self.logger.error(e)
            raise DbUserCreateError(str(e))
        else:
            isSuccess = True
            self.logger.info('Create Cassandra Keyspace[' + cassandra_user + '] Success!')
        finally:
            try:
                sm.close()
            except Exception as e:
                self.logger.error(e)
        
        return { 
                'username': cassandra_user,
                'password': cassandra_pass,
                'db': cassandra_db,
                'success' : isSuccess ,
               }

        

    def __do_drop_cassandrauser(self, db_item):
        sysuser = db_item['admin_user']
        syspass = db_item['admin_passwd']
        vip = db_item['vip']
        port = db_item['db_port']
        sid = db_item['sid']
        olduser = db_item['olduser']
        cred = None
        if(sysuser is not None and syspass is not None) :
            cred = {'username' : sysuser, 'password' : syspass}                

        try:
            '''
                before connect, modify the connect string as:
                "['vip:port','vip2:port'...]" so that this can be used in ConnectionPool()
                the vip str should be like "vip1,vip2,vip3",
                and we regard all port are the same.
                SystemManager.server didn't support a array of server list now, only ConnectionPool.server_list support
            '''            
            vip_list = vip.split(',')            
            for myvip in vip_list:
                try:
                    cons = myvip + ':' + str(port)
                    sm = SystemManager(server=cons, credentials=cred)
                    break
                except: 
                    pass            
                       
            sm = SystemManager(server=cons, credentials=cred)
            
            #check if user exist: by check if database name exist(database name and username are the same) 
            database_names = sm.list_keyspaces()
            if olduser in database_names:
                sm.drop_keyspace(olduser)

        except Exception as e:
            self.logger.error(e)
            raise DbUserDropError(str(e)) 
        else:
            self.logger.info('Drop Cassandra Keyspace [' + olduser + '] Success!')
        finally:
            sm.close()
            
...

Of course, it’s a quite simple function. But it’s a good and great start 🙂

Advertisements

About Alex Zeng
I would be very happy if this blog can help you. I appreciate every honest comments. Please forgive me if I'm too busy to reply your comments in time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: