Ticket #6243: runscripts_1.diff

File runscripts_1.diff, 6.3 KB (added by poelzi, 8 years ago)

patch and docs for runscripts

  • django/core/management/commands/runscript.py

     
     1from django.core.management.base import BaseCommand
     2from django.core.management.color import no_style
     3from optparse import make_option
     4import sys
     5import os
     6
     7try:
     8    set
     9except NameError:
     10    from sets import Set as set   # Python 2.3 fallback
     11
     12class Command(BaseCommand):
     13    option_list = BaseCommand.option_list + (
     14        make_option('--verbosity', action='store', dest='verbosity', default='1',
     15            type='choice', choices=['0', '1', '2'],
     16            help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
     17        make_option('--fixtures', action='store_true', dest='infixtures', default=False,
     18            help='Only look in app.fixtures subdir'),
     19        make_option('--noscripts', action='store_true', dest='noscripts', default=False,
     20            help='Look in app.scripts subdir'),
     21    )
     22    help = 'Runs a script in django context.'
     23    args = "script [script ...]"
     24
     25    def handle(self, *scripts, **options):
     26        from django.db.models import get_apps
     27
     28        subdirs = []
     29
     30        if not options.get('noscripts'):
     31            subdirs.append('scripts')
     32        if options.get('infixtures'):
     33            subdirs.append('fixtures')
     34        verbosity = int(options.get('verbosity', 1))
     35        show_traceback = options.get('traceback', False)
     36
     37        if len(subdirs) < 1:
     38            print "No subdirs to run left."
     39            return
     40
     41        if len(scripts) < 1:
     42            print "Script name required."
     43            return
     44
     45        def run_script(name):
     46            if verbosity > 1:
     47                print "check for %s" % name
     48            try:
     49                t = __import__(name, [], [], [" "])
     50
     51                if verbosity > 0:
     52                    print "Found script %s ..." %name
     53                if hasattr(t, "run"):
     54                    if verbosity > 1:
     55                        print "found run() in %s. executing..." % name
     56                    # TODO: add arguments to run
     57                    try:
     58                        t.run()
     59                    except Exception, e:
     60                        if verbosity > 0:
     61                            print "Exception while running run() in %s" %name
     62                        if show_traceback:
     63                            raise
     64                else:
     65                    if verbosity > 1:
     66                        print "no run() function found."
     67                   
     68            except ImportError:
     69                pass
     70
     71
     72        for app in get_apps():
     73            app_name = app.__name__.split(".")[:-1] # + ['fixtures']
     74
     75            for subdir in subdirs:
     76                for script in scripts:
     77                    run_script(".".join(app_name + [subdir, script]))
     78
     79        # try app.DIR.script import
     80        for script in scripts:
     81            sa = script.split(".")
     82            for subdir in subdirs:
     83                nn = ".".join(sa[:-1] + [subdir, sa[-1]])
     84                run_script(nn)
     85
     86            # try direct import
     87            if script.find(".") != -1:
     88                run_script(script)
     89
     90
  • django/core/management/commands/syncdb.py

     
    136136        # Install the 'initial_data' fixture, using format discovery
    137137        from django.core.management import call_command
    138138        call_command('loaddata', 'initial_data', verbosity=verbosity)
     139        call_command('runscript', 'initial_data', verbosity=verbosity, noscripts=True, fixtures=True)
  • docs/django-admin.txt

     
    344344.. _FastCGI deployment documentation: ../fastcgi/
    345345.. _flup: http://www.saddi.com/software/flup/
    346346
     347runscript <scriptname scriptname>
     348------------------------------------------------
     349
     350**New in Django development version**
     351
     352Sometimes its very usefull to have simple scripts in applications which
     353will be called in django's context.
     354The runscript command searches for subdirectories named ``scripts`` and
     355``fixtures`` if the --fixtures parameter is given.
     356There are two types of simple script types supported:
     357
     358    * scripts in fixtures.
     359      These scripts are run when runscript
     360      ``--fixtures`` option is set. The initial_data.py script is
     361      executed after loaddata in syncdb
     362    * scripts in scripts.
     363      These are the default scripts which will be started with
     364      runscript [scriptname]. These can be disabled with ``--noscripts``
     365      parameter.
     366      A good example is a script called daily_cleanup.py in every application
     367      which has to do a daily cleanup.
     368
     369After import the run() method is executed. You should write::
     370
     371    def run(*args, **kwargs):
     372        dosomething()
     373        ...
     374
     375<scriptname>
     376scriptname can be relative or absolut
     377
     378        django-admin.py runscript somescript
     379
     380will walk trough all application scripts subdirectories and
     381execute somescript.run()
     382
     383    django-admin.py runscript myapp.somescript
     384
     385will execute myapp.scripts.somescript.run()
     386
     387    django-admin.py runscript --fixtures --noscripts --verbosity=2 initial_data
     388
     389will call all initial_data scripts in fixtures subdirectories
     390of all applications, printing verbose output what the script does.
     391This is is called by syncdb.
     392
     393**Please remember that directories containing scripts also need a __init__.py**
     394
     395--fixtures
     396~~~~~~~~~~~
     397
     398Looks in the fixtures subdirectory.
     399
     400--noscripts
     401~~~~~~~~~~~
     402
     403Don't look in scripts subdirectory for a match.
     404
     405--verbosity
     406~~~~~~~~~~~
     407
     408Use ``--verbosity`` to specify the amount of notification and debug information
     409that ``django-admin.py`` should print to the console.
     410
     411        * ``0`` means no input.
     412        * ``1`` means normal input (default).
     413        * ``2`` means verbose input.
     414
     415Example usage::
     416
     417    django-admin.py runscript --verbosity=2 initial_data
     418
     419
     420
    347421runserver [optional port number, or ipaddr:port]
    348422------------------------------------------------
    349423
Back to Top