我想让 Django 的管理命令 shell 在每个 Python 表达式执行的前后 运行一个脚本。例如:
(想想我正在使用命令 python3 manage.py shell --ipython 进入 shell。)
In [1]: from api.models import Student
In [2]: new_student = Student.objects.create(name="John Doe", number=123)
In [3]: new_student.number
Out[3]: 123
In [4]: new_student.name
Out[4]: "John Doe"
我想将它们的表达式和输出发送到 Slack channel 。为此,我需要在每个表达式之前和之后运行一个 Python 脚本,它需要表达式或输出记录到我的 Slack channel 。
对于上面的示例,脚本将记录表达式,例如 "new_student.number",以及它们的输出 - 如果存在,当然 - 例如 "123",到 Slack channel 。
我试过使用 django-extensions模块,将其 shell_plus 命令与前信号和后信号 一起使用。但它只是在 运行 plus_shell 之前和之后 调用信号。因此,我想做的是在每个命令/表达式之前和之后运行这些信号处理程序。
有没有办法使用配置、模块甚至编写自定义管理命令来实现这一点?
请您参考如下方法:
我不确定 shell 是否真的以您想要的方式支持它,但是您可以通过编写包装函数然后通过该包装函数调用所有命令来快速破解。
def wrap_fun(expr):
val=exec(expr)
## run/call your script with argument expr and val
print(val)
然后将所有函数调用为
In [1]: wrap_fun('from api.models import Student')
In [2]: wrap_fun('new_student = Student.objects.create(name="John Doe", number=123)')
In [3]: wrap_fun('new_student.number')
Out[3]: 123
In [4]: wrap_fun('new_student.name')
Out[4]: "John Doe"
您可以使用 subprocess 模块来加载您的 python 脚本(发送松弛消息)并调用它。或者,您可以将此函数和 slack 脚本添加到模块中的 Django 项目,通过 DEBUG=true 等本地设置控制发送行为,然后直接从 shell 调用它。
