自定义命令
Masonite 中的命令普遍用于让开发工作更加简单。命令的使用范围从创建控制器和模型到安装包及发布资源。
Masonite 使用cleo包实现 shell 命令特性。
运行如下命令可以显示 Masonite 可用的命令:
python craft
该命令会显示 Masonite 已有的命令列表。
每个命令有一屏文档描述命令可用的参数和选项。要查看命令文档,在命令前使用 help
。比如,查看 serve
命令的帮助文档,可以运行如下代码:
python craft help serve
创建命令
可以使用简单命令类来创建新的命令,该命令类继承 Masonite Command
类:
from masonite.commands import Command
class MyCommand(Command):
"""
Description of Command
command:signature
{user : A positional argument for the command}
{--f|flag : An optional argument for the command}
{--o|option=default: An optional argument for the command with default value}
"""
def handle(self):
pass
命令名,描述和参数都是从命令的注释文档(docstring)中解析而来。
名称和描述
注释文档(docstring)应该从命令描述开始:
"""
Description of Command
"""
然后紧接着一行空行,紧接着跟上你定义的命令名称。
"""
Description of Command
command_name
"""
定位参数
在命令名之后的注释文档中,紧接着应该是参数。参数用一个缩进定义并放在花括号中。
定位(强制性的)参数不使用中横线(-
或 --
)定义。
以下是如何使用描述定义名为 name
的位置参数:
"""
{name : Description of the name argument}
"""
在命令内部,可以使用 self.argument(arg_name)
检索位置参数
def handle(self):
name = self.argument("name")
可选参数
可选参数用破折号定义,可以在命令调用中以任何顺序使用。可选参数 --force
可以有一个短名称 --f
。
以下是如何使用描述定义两个可选参数 iterations
和 force
:
"""
command_name
{--iterations : Description of the iterations argument}
{--f|force : Description of the force argument}
"""
请注意我们如何为 force
参数提供简短版本,但没有为 iterations
参数提供
现在你可以像这样使用命令:
python craft command_name --f --iterations
python craft command_name --iterations --force
如果可选参数需要一个值,你应该添加 =
后缀:
"""
command_name
{--iterations= : Description of the iterations argument}
"""
在这里,当使用 iterations
时,用户应该提供一个值。
python craft command_name --iterations 3
python craft command_name --iterations=3
如果参数可能有值,也可能没有值,你可以使用后缀 =?
代替。
"""
command_name
{--iterations=?: Description of the iterations argument}
"""
python craft command_name --iterations
python craft command_name --iterations 3
最后,如果在没有提供值的情况下应该使用默认值,请添加后缀 ={default}
:
"""
command_name
{--iterations=3: Description of the iterations argument}
"""
# iterations will be equal to 3
python craft command_name --iterations
# iterations will be equal to 1
python craft command_name --iterations 1
在命令内部,可以使用 self.option(arg_name)
检索可选参数
def handle(self):
name = self.option("iterations")
打印消息
你可以使用不同的格式将消息打印到控制台:
self.info("Info Message")
:将以绿色输出消息self.warning("Warning Message")
:将以黄色输出消息self.error("Error Message")
: 将以红色粗体输出消息self.comment("Comment Message")
:将以浅蓝色输出消息
高级功能
你可以在 Cleo 文档 中找到有关创建命令的更多信息和更多功能。
Masonite Command
类继承了 Cleo Command
类,因此你应该能够在以下情况下使用所有 Cleo 功能
创建命令。
注册命令
你可以在 Service Provider 内(如果你没有,你应该创建一个)将命令注册到 Masonite 的 服务容器:
add()
方法接受一个或多个命令:app/providers/AppProvider.py
from some.place.YourCommand import YourCommand
class AppProvider(Provider):
def __init__(self, application):
self.application = application
def register(self):
self.application.make('commands').add(YourCommand(self.application))
当你运行 python craft
时,你现在将看到你添加的命令。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。