python manage.py xxx自定义参数执行命令实现相关操作
在项目中有一些功能或需求需要通过命令执行,对应用做一些操作或修改,比如项目数据初始化、数据更新、定时任务等,通过执行命令或配置crontab就可以实现需求,下面简单介绍一下Django项目中如何实现相关功能。
比如有需求需要执行一条命令python manage.py init
对项目初始化数据,经过查阅资料了解自定义参数存在app/management/commands
目录下,在commands
创建init.py
文件,就可以执行python manage.py init
命令运行init.py
文件中的逻辑。
官方文档:https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/
创建/management/commands目录
重要: 首先要明确,/management/commands
目录一定是在注册的APP的中才会生效,而且/management/commands
每个目录下都要有__init__.py
文件。
创建test
应用,使用django-admin startapp test
或python manage.py startapp test
命令创建APP,然后按照下面的目录结构在生成的test
文件夹下创建management
、commands
文件夹,然后每个文件夹内添加__init__.py
文件。
具体目录结构如下:
test/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
_private.py
hello_word.py
tests.py
views.py
完善hello_word.py文件
已经看到上述目录中有一个hello_word.py文件,按照国际惯例执行python manage.py hello_world
输出Hello World!
,具体代码如下:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
# 帮助文本, 一般备注命令的用途及如何使用。
help = 'Some help texts'
# 处理命令行参数,可选
def add_arguments(self, parser):
pass
# 核心业务逻辑
def handle(self, *args, **options):
self.stdout.write('Hello World!')
代码修改完,这时候当你开心的执行python manage.py hello_world
,发现报错而且不好用:
Unknown command: 'hello_world'
Type 'manage.py help' for usage.
这是因为上面提到的/management/commands
目录一定是在注册的APP的中才会生效,所以要在setting.py
中注册APP:
INSTALLED_APPS = [
...
'test',
]
这时候再执行python manage.py hello_world
就好了:
(venv) tutorial>python manage.py hello_world
Hello World!
到这里就可以接着向下看进阶内容了。
add_arguments()函数
add_arguments()
函数可以配置命令传递的参数,比如执行python manage.py hello_world -t Django
,输出输出Hello Django!
可以修改成:
# 处理命令行参数,可选
def add_arguments(self, parser):
parser.add_argument("-t", "--text", type=str, default='World', help="替换的字符串")
# 核心业务逻辑
def handle(self, *args, **options):
text = options.get("text")
self.stdout.write('Hello %s!' % text)
add_argument()函数
注意这个add_argument()
和上面的少了一个s
,是python的自带的方法,这里对parser.add_argument()
函数做个简单介绍。
详细内容可参考官网文档:https://docs.python.org/3/library/argparse.html#the-add-argument-method
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
参数 | 说明 |
---|---|
name or flags | 执行的名称参数名,也就是上述的"-t", "--text" |
default | 参数默认值,如果参数没传值则获取默认数据 |
type | 参数类型 |
choices | 参数可选项,如果有此配置则参数值必须在列表中 |
help | 参数说明 |
小结
到此本章就结束了,上述简单介绍了Django通过命令方式执行一些 操作的方法,具体详细还要参考官方的文档。
万变不离其宗,掌握了基础后面的具体使用就根据自己的情况而定就好了。