วันจันทร์ที่ 8 กรกฎาคม พ.ศ. 2556

Create Script to Run Django Method

Sample script to run Django method from command line.
Assume there is
- /path/to/my/project/settings.py for Django settings
- /path/to/my/project/mymodule/models/mymodel.py
- Django class myclass in the above mymodel.py with method mymethod()

#!/usr/bin/python2.7

import os
import sys

sys.path.append('/path/to/my/project/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

from mymodule.models.mymodel import myclass

myclass.mymethod()


Sample script that output result to a log file with date&time in file name as below (can use with Python 2.6+).
#!/usr/bin/python2.7
from __future__ import print_function
import os
import sys

sys.path.append('/path/to/my/project/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

from datetime import datetime
from mymodule.models.mymodel import myclass

t = datetime.now()
fname = '/path/to/log/folder/%s.log' % t.strftime('%Y-%m-%d_%H%M%S')
f = open(fname, 'w')
print('done some task with result = %s' % myclass.method(), file=f)
f.close()

a log will be written to file like /path/to/log/floder/2013-07-09_151201.log

ไม่มีความคิดเห็น:

แสดงความคิดเห็น