Created
January 11, 2016 13:46
-
-
Save fbidu/a96582bd7bbd90e47e70 to your computer and use it in GitHub Desktop.
Script that quickly initializes a MySQL database and account for use in dev environments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
""" | |
Script that quickly initializes a MySQL database and account for use in dev | |
environments | |
""" | |
import argparse | |
from string import ascii_uppercase, digits | |
from random import choice | |
from cymysql import connect | |
DB_HOST = 'localhost' | |
DB_USER = 'root' | |
DB_PASS = 'your_password' | |
LIMIT_CONNECTION_TO = 'localhost' | |
def main(): | |
parser = argparse.ArgumentParser(description= | |
"Creates a new MySQL database and user " + | |
"fast use in development environment") | |
parser.add_argument('-n', '--name', help="Name of the application. This " + | |
"will be used as user and db name", | |
required=True) | |
args = parser.parse_args() | |
name = args.name | |
# Generating a new password | |
password = ''.join(choice(ascii_uppercase + digits) for _ in range(6)) | |
# Script for creating the user | |
create_user = "CREATE USER '{}'@'{}' IDENTIFIED BY '{}'".format( | |
name, LIMIT_CONNECTION_TO, password | |
) | |
create_database = "CREATE DATABASE %s" % name | |
grant = "GRANT ALL ON %s.* TO '%s'@'%s'" % (name, name, LIMIT_CONNECTION_TO) | |
connection = connect(DB_HOST, DB_USER, DB_PASS) | |
cursor = connection.cursor() | |
cursor.execute(create_user) | |
cursor.execute(create_database) | |
cursor.execute(grant) | |
connection.close() | |
print("The password for the created user is %s" % password) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment