[Python] Generare le impostazioni MySQL per WordPress

Nel tutorial di oggi vi mostreremo come creare uno script python che genera automaticamente le impostazioni MySQL per il file di configurazione "wp-config.php" di WordPress.

 
#!/usr/bin/python
import string
import random
import sys
import MySQLdb
 
# pass_gen will generate a random string of characters
 
def pass_gen(size=10,
             chars=string.ascii_uppercase +
             string.ascii_lowercase +
             string.digits):
    return ''.join(random.choice(chars) for x in range(size))
 
def main(argv):
    sitename = argv[0]
 
    '''
       Generate semi-random names
       Random number is based off of 16 minus the length of databse name given
    '''
 
    db_name = sitename + pass_gen(16 - len(sitename))
    db_user = sitename + pass_gen(16 - len(sitename))
    db_password = sitename + pass_gen(16 - len(sitename))
 
    # Create the database with the settings
    db = MySQLdb.connect(host='localhost', user='root', passwd='Superb33')
    cur = db.cursor()
 
    create_db_sql = 'CREATE DATABASE %s' % (db_name)
    grant_user_sql = 'GRANT ALL PRIVILEGES ON %s.* to "%s"@"localhost" \
     identified by "%s"' % (db_name, db_user, db_password)
    cur.execute(create_db_sql)
    cur.execute(grant_user_sql)
 
    # Concatnate DB Strings
    db_name_string = "/** The name of the database for WordPress */\
        \ndefine('DB_NAME', '%s');\n" % (db_name)
    db_user_string = "/** MySQL database username */\
        \ndefine('DB_USER', '%s');\n" % (db_user)
    db_pass_string = "/** MySQL database password */\
        \ndefine('DB_PASSWORD', '%s');\n" % (db_password)
 
    # Print the result
    print "Copy and paste this to the wp-config.php settings file\n"
    print db_name_string
    print db_user_string
    print db_pass_string
 
if __name__ == "__main__":
    main(sys.argv[1:])