Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miraculixx/25bd70038988cc7912a3 to your computer and use it in GitHub Desktop.
Save miraculixx/25bd70038988cc7912a3 to your computer and use it in GitHub Desktop.
with inputfile for temporary file content
@task
def listlocaldbs():
"""
list dbregistry in $HOME/dbregistry.txt
"""
registryfile = os.path.expanduser('~/dbregistry.txt')
with open(registryfile, 'r') as f:
print f.read()
@task
def createlocaldb(dbname=None, username=None, password=None):
"""
Create a local database and grant all rights to given user with
given password. Will create/update file $HOME/dbregistry.txt with
the list of dbs, usernames and passwords. Make sure this is a
save directory.
"""
username = username or ("%s" % uuid4())[0:15]
password = password or ("%s" % uuid4())[0:15]
while not dbname:
dbname = dbname or prompt('dbname?')
sql = (
"drop database if exists %s" % dbname,
"create user '%s'@'localhost' IDENTIFIED BY '%s'" % (username, password),
"create database %s CHARACTER SET utf8 COLLATE utf8_general_ci" % dbname,
"grant all on %s.* to '%s'@'localhost'" % (dbname, username),
"exit",
)
print sql
with inputfile(";\n".join(sql)) as sqlf:
local('cat % s | mysql -udbadmin -pdbadmin ' % sqlf.name)
print "created db=%s user=%s password=%s" % (dbname, username, password)
registryfile = os.path.expanduser('~/dbregistry.txt')
with open(registryfile, 'a') as f:
f.write('db=%s,user=%s,password=%s\n' % (dbname, username, password))
@task
def dbshell(dbname=None):
"""
connect to a database in $HOME/dbregistry.txt. Simple
way to connect using just the dbname.
"""
from parse import parse
registryfile = os.path.expanduser('~/dbregistry.txt')
dbindex = {}
with open(registryfile, 'r') as f:
content = f.readlines()
dbs = [parse('db={},user={},password={}', db) for db in content]
for db in dbs:
db, user, password = db
dbindex[db] = user, password,
dbname = dbname or prompt_list('select db', dbindex.keys())
user, password = dbindex[dbname]
local('mysql -u%s -p%s %s' % (user, password, dbname))
@contextlib.contextmanager
def inputfile(content=None):
"""
create a named tempfile with content content.
returns the File object
Use:
from fabic
from fabutil import inputfile
with inputfile('some string') as f:
local('cat %s' % f.name)
"""
try:
f = NamedTemporaryFile()
f.write(content)
f.flush()
yield f
except RuntimeError, err:
print '[ERROR]', err
finally:
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment