Login

script for run a django task

Author:
tailorcai
Posted:
June 7, 2007
Language:
Python
Version:
.96
Tags:
task console script
Score:
1 (after 3 ratings)

when running a console script to access django or your models, you need to setup django environment properly and that is very annoying if you have quite a few scripts. this script can be used as a wrapper just like the manage.py.

put it in your project root and type this:

python run.py myproj.appname.filename.functionname [arguments]

and define your function as def functionname(argv[]): ...

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/local/bin/python
#coding:utf-8
import sys, os
import datetime
from django.core.management import setup_environ, DEFAULT_ACTION_MAPPING, startapp
try:
    import settings # Assumed to be in the same directory.
except ImportError:
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)

project_directory = setup_environ(settings)
project_name = os.path.basename(project_directory)
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % project_name

if __name__ == "__main__":    
    if len(sys.argv) <=1:
        sys.stderr.write("run xxx.yyy.run p1 p2 p2")
        sys.exit(1)

    classpath = sys.argv[1].split('.')
    if len(classpath) > 0:
        pkg = '.'.join(classpath[:-1])
        fr = classpath[-1]
    else:
        sys.stderr.write("path must has form of aaa.bbb")
        sys.exit(1)
        
    try:
        mod = __import__( pkg, '', '', fr)
    except ImportError:
        sys.stderr.write("path can't be found")
        sys.exit(1)

    cls = getattr(mod, fr)
    
    params = []
    for i in range(0,len(sys.argv)):
        if i != 1:
            params.append( sys.argv[i])
    
    cls(params)
    
    
    

More like this

  1. cron/console bootstrap django by nstrite 7 years, 11 months ago
  2. SQL Log To Console Middleware by davepeck 5 years, 11 months ago
  3. Middleware for printing of exception to console by dballanc 7 years, 10 months ago
  4. change SITE_ID on fly by m-garanin@yandex.ru 6 years, 10 months ago
  5. Quiet runserver by danielroseman 5 years, 1 month ago

Comments

Please login first before commenting.