Package spammcan :: Module bootstrap
[hide private]

Source Code for Module spammcan.bootstrap

 1  """Functions for bootstrapping the database used by the commands module.""" 
 2   
 3  __all__ = [ 
 4      'bootstrap_model', 
 5      'create_formats', 
 6      'create_tables', 
 7      'create_default_user' 
 8  ] 
 9   
10  from getpass import getpass 
11   
12  from turbogears.database import get_engine, session 
13  from spammcan.model import metadata, Format, Style, User 
14   
15  # functions for populating the database 
16   
17 -def bootstrap_model(clean=False, create_user=False):
18 """Create all database tables and fill them with default data.""" 19 create_tables(clean) 20 create_formats() 21 create_styles() 22 if create_user: 23 create_default_user(options.user)
24
25 -def create_default_user(user_name):
26 """Create a default user.""" 27 try: 28 u = User.by_user_name(user_name) 29 except: 30 u = None 31 if u: 32 print _(u"User '%s' already exists in database.") % user_name 33 return 34 while True: 35 password = getpass(_(u"Enter password for user '%s': ") % user_name).strip() 36 password2 = getpass(_(u"Confirm password: ")).strip() 37 if password != password2: 38 print _(u"Passwords do not match.") 39 else: 40 break 41 u = User(user_name=user_name, display_name=u"Default User", 42 email_address=u"%s@nowhere.xyz" % user_name, password=password) 43 session.save(u) 44 session.flush() 45 print _(u"User '%s' created.") % user_name
46
47 -def create_formats():
48 """Populate the 'format' table.""" 49 from pygments.lexers import get_all_lexers 50 51 if Format.query().count(): 52 return 53 lexers = sorted(get_all_lexers(), key=lambda k: k[0].lower()) 54 for name, aliases, extensions, mimetypes in lexers: 55 f = Format(name=aliases[0], display_name=unicode(name)) 56 session.save(f) 57 session.flush() 58 print _(u"Populated 'format' table.")
59
60 -def create_styles():
61 """Populate the 'style' table.""" 62 from pygments.styles import get_all_styles 63 64 if Style.query().count(): 65 return 66 styles = sorted(get_all_styles(), key=lambda k: k[0].lower()) 67 for name in styles: 68 s = Style(name=name, display_name=unicode(name.capitalize())) 69 session.save(s) 70 session.flush() 71 print _(u"Populated 'style' table.")
72
73 -def create_tables(drop_all=False):
74 """Create all tables defined in the model in the database. 75 76 Optionally drop existing tables before creating them. 77 78 """ 79 if drop_all: 80 print "Dropping all database tables defined in model." 81 metadata.bind = get_engine() 82 if drop_all: 83 metadata.drop_all() 84 metadata.create_all() 85 print _(u"All database tables defined in model created.")
86