Login

script for run a django task

Author:
tailorcai
Posted:
June 7, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.