2

我想让 Django 的管理命令在每个 Python 表达式执行之前和之后shell运行一个脚本。例如:

(想想我正在使用命令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 频道。为此,我需要在每个表达式之前和之后运行 Python 脚本,该脚本将表达式或输出记录到我的 Slack 频道。

对于上面的示例,脚本会将表达式(例如"new_student.number")及其输出(如果存在,当然) (例如"123",例如 )记录到 Slack 通道

我尝试使用django-extensions模块,将其shell_plus命令与pre 和 post 信号一起使用。但它只是在运行 plus_shell 之前和之后调用信号。因此,我想做的是在每个 command/expression 之前和之后运行这些信号处理程序。

有没有办法使用配置、模块甚至编写自定义管理命令来实现这一点?

4

1 回答 1

-1

我不确定外壳是否真的会以您想要的方式支持它,但是您可以通过编写一个包装函数然后通过该包装函数调用所有命令来快速破解。

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 调用它。

于 2018-09-24T14:07:10.723 回答