Changes between Initial Version and Version 1 of CookBookScriptsMiniFlush


Ignore:
Timestamp:
08/20/2005 09:53:12 PM (14 years ago)
Author:
garthk
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • CookBookScriptsMiniFlush

    v1 v1  
     1Sick of running {{{django-admin}}} repeatedly to {{{init}}} your site and {{{install}}} each of your apps when you've made lots of changes to the model? {{{miniflush.py}}} will do all the heavy lifting for you:
     2
     3{{{
     4import os
     5from os.path import isdir, isfile, join, dirname
     6import django.core.management, django.core
     7
     8def find_site():
     9    """Find the site by looking at the environment."""
     10    try:
     11        settings_module = os.environ['DJANGO_SETTINGS_MODULE']
     12    except KeyError:
     13        raise AssertionError, "DJANGO_SETTINGS_MODULE not set."
     14
     15    settingsl = settings_module.split('.')
     16    site = __import__(settingsl[0])
     17    settings = __import__(settings_module, {}, {}, settingsl[-1])
     18    return site, settings
     19   
     20def delete_db(settings):
     21    """Delete the old database."""
     22    engine = settings.DATABASE_ENGINE
     23    if engine == 'sqlite3':
     24        try:
     25            os.unlink(settings.DATABASE_NAME)
     26        except OSError:
     27            pass
     28    elif engine == 'mysql':
     29        import _mysql
     30        s = _mysql.connect(host=settings.DATABASE_HOST,
     31                           user=settings.DATABASE_USER,
     32                           passwd=settings.DATABASE_PASSWORD)
     33        for cmd in ['drop database if exists %s',
     34                    'create database %s']:
     35            s.query(cmd % settings.DATABASE_NAME)
     36    else:
     37        raise AssertionError, "Unknown database engine %s", engine
     38
     39def init_and_install(site):
     40    """Initialise the site and install any applications. Applications
     41    are found by looking for ``sitename/apps`` in sitename.apps."""
     42    django.core.management.init()
     43    appdir = join(dirname(site.__file__), 'apps')
     44    for name in [name for name in os.listdir(appdir)
     45                if isdir(join(appdir, name))
     46                and isfile(join(appdir, name, '__init__.py'))]:
     47        try:
     48            app = django.core.meta.get_app(name)
     49            django.core.management.install(app)
     50        except AttributeError, ex:
     51            pass # Exercise for reader: be more specific
     52
     53def main():
     54    """Flush it all, baby!"""
     55    try:
     56        site, settings = find_site()
     57        delete_db(settings)
     58        init_and_install(site)
     59    except AssertionError, ex:
     60        print ex.args[0]
     61
     62if __name__ == '__main__':
     63    main()
     64}}}
Back to Top