Skip to content

Instantly share code, notes, and snippets.

@Uninen
Created July 1, 2011 22:40
Show Gist options
  • Save Uninen/1059541 to your computer and use it in GitHub Desktop.
Save Uninen/1059541 to your computer and use it in GitHub Desktop.
DbDamnit -- Automagic db configuration for Django
# -*- coding: utf-8 -*-
"""
dbdamnit.py is a management command for creating and configuring MySQL
database settings automagically for Your Django project. This code
uses convention over configuration, feel free to modify and use it
for your own projects as You like.
Happy hacking! :)
- @uninen
--
Copyright (c) 2011, Ville Säävuori <http://www.unessa.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import os
import string
from random import choice
import _mysql
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
"""
USAGE:
Put your db credentials (with sufficient privilleges) to ~/.mysql and this
command will
1) create a db for you,
2) create a db user with a random password for you,
3) save the configuration in conf/my.cnf and
4) add the configuration in project/settings/common_settings.py
Example content for ~/.mysql:
localhost::myuser::mypasswd
In your common_settings.py you need this:
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
"""
args = ''
help = 'Creates MySql database, user and Django config for you.'
def handle(self, *args, **options):
try:
PROJECT_ROOT = os.environ['HG_PROJECT_ROOT']
PROJECT_NAME = os.environ['PROJECT_NAME']
f = open('%s/.mysql' % os.environ['HOME'])
host, mysql_user, mysql_password = f.read().split('::')
f.close()
new_user = PROJECT_NAME
new_database = PROJECT_NAME
new_password = ''.join([choice( \
string.letters + \
string.digits + \
'#$%&()+,-.:;<>?@[]^{|}~' \
) for i in range(14)])
db = _mysql.connect("localhost", mysql_user, mysql_password)
print "Creating database %s.." % new_user,
db.query("CREATE DATABASE %s;" % new_user)
print "Done."
print "Creating user %s.." % new_user,
db.query("GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'%s' IDENTIFIED \
BY '%s';" % (new_database, new_user, host, new_password))
print "Done."
db.query("FLUSH PRIVILEGES;")
print "Flushed privileges."
print "Creating my.cnf..",
my_conf = open('%s/conf/my.cnf' % PROJECT_ROOT, 'w')
contents = """[client]
database = %s
user = %s
password = %s
default-character-set = utf8
""" % (new_database, new_user, new_password)
my_conf.write(contents)
my_conf.close()
print "Done."
print "Adding db config to common_settings..",
common_settings = open('%s/%s/settings/common_settings.py' % \
(PROJECT_ROOT, PROJECT_NAME), 'a')
contents = """
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(PROJECT_ROOT, 'conf/my.cnf'),
},
}
}
"""
common_settings.write(contents)
common_settings.close()
print "Done."
db.close()
self.stdout.write('Database config OK! Have a nice day :)\n')
except _mysql.ProgrammingError, e:
raise CommandError('Problen with database. %s' % e)
except:
raise CommandError('Please put your MySQL credentials to \
~/.mysql in order to use this script.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment