I'm creating tool to add new virtualhost on UNIX-box. One of tasks is to add a new user and database to MariaDB (aka MySQL) server. In fact - this my first 'real' attempt to use OOP.
Here is class, which I created for it:
class mysqlUserDb:
warnings.filterwarnings('error')
def __init__(self):
self.root = 'root'
self.host = 'localhost'
self.rootpw = 'p@ss'
try:
print '\nChecking MySQL connection...'
self.db = MySQLdb.connect(self.host, self.root, self.rootpw)
self.cursor = self.db.cursor()
self.cursor.execute('select version()')
print 'Connection OK, proceeding.'
except MySQLdb.Error as error:
print 'Error: %s ' %error + '\nStop.\n'
sys.exit()
def createdb(self, db):
print '\nCreating database...'
try:
self.cursor.execute('create database if not exists ' + db)
self.cursor.execute('show databases like ' + '\'' + db + '\'')
dbs = self.cursor.fetchone()
print 'Database created: %s' %dbs
except Warning as warn:
print 'Warning: %s ' %warn + '\nStop.\n'
sys.exit()
def grants(self, user, userpass, db):
print '\nGrant privilegies... '
try:
self.cursor.execute('grant all on ' + db + '.*' + 'to ' + '\'' + user + '\'' + "@'localhost'" + 'identified by ' + '\'' + userpass + '\'')
self.cursor.execute('select user, db from mysql.db where db=' + '\'' + db + '\'')
grs = self.cursor.fetchall()
print 'Access granted: %r' %grs
except Warning as warn:
print 'Warning: %s ' %warn + '\nStop.\n'
sys.exit()
except MySQLdb.Error as error:
print 'Error: %s ' %error + '\nStop.\n'
sys.exit()
def __del__(self):
print '\nFinishing operations...'
self.cursor.close()
self.db.close()
print 'Done.\n'
Next, in tool it call like:
import createvhostFunctsClass as fun
mysql = fun.mysqlUserDb()
mysql.createdb('db_2')
mysql.grants('user', 'pass', 'db_2')
del mysql
(it's just example, not included yet in tool).
And its works like:
$ ./myclass.py Checking MySQL cconnection... Connection OK, proceeding. Creating database... Database created: db_2 Grant privilegies... Access granted: ('user', 'db_2') Finishing operations... Done.
I'm pretty sure, here is lot of stuff, which I missed or did incorrectly (or not the "Python way").
Also, I'm not sure - which way better:
- create methods for each action (add database, add user) and just call this methods from script (currently done)
- create one method, which will get needed action ('create database lalala') as argument and call this method several times in script