Granting access in Python
Using MySQLdb to enable user privileges is not more difficult than doing so in MySQL itself. As with creating and dropping users, we simply need to form the statement and pass it to MySQL through the appropriate cursor.
As with the native interface to MySQL, we only have as much authority in Python as our login allows. Therefore, if the credentials with which a cursor is created has not been given the GRANT option, an error will be thrown by MySQL and MySQLdb, subsequently.
Assuming that user skipper has the GRANT option as well as the other necessary privileges, we can use the following code to create a new user, set that user's password, and grant that user privileges:
#!/usr/bin/env python
import MySQLdb
host = 'localhost'
user = 'skipper'
passwd = 'secret'
mydb = MySQLdb.connect(host, user, passwd)
cursor = mydb.cursor()
try:
mkuser = 'symphony'
creation = "CREATE USER %s@'%s'" %(mkuser, host)
results = cursor.execute(creation)
print "User creation...