# django manage.py扩展自定义命令
环境: mac django1.10.3
在实际的项目开发过程中,我们可能要执行某脚本初始化数据库,可能要启动多个服务,比如启动celery,redis等。要是直接执行python mange.py celery/redis那该多方便啊!,能把这些命令整合到django框架的manage.py中吗?
示例-初始化数据
通过执行python manage.py initdata命令初始化数据,执行此命令后,调用某数据初始化脚本文件,进行数据初始化。
1.创建项目 myproject
略
2.创建app myapp,并配置settings.py
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
3.在myapp下建management.commands模块
建立后的目录如下:
4.在commands下建initdata.py文件
from django.core.management.base
import BaseCommand, CommandError
import os
import logging
import subprocess
INTERPRETER =
"/usr/bin/python"
class Command(BaseCommand):
def handle(self, *args, **options):
if not os.path.exists(INTERPRETER):
log.error(
"Cannot find INTERPRETER at path \"%s\"." % INTERPRETER)
dirs = os.path.join(os.path.dirname(__file__),
'../../..')
processor = dirs +
"/init/data.py"
pargs = [INTERPRETER, processor]
subprocess.Popen(pargs)
5.编写data.py
if __name__ ==
'__main__':
print 'ok'
6.执行python manage.py initdata
转载请注明原文地址: https://ju.6miu.com/read-2491.html