我正在使用自定义内容类型在 Drupal 7 中创建网站。在创建节点时,我需要以某种方式触发 python 脚本(由其他人开发)的执行,该脚本将:
- 从当前正在创建的节点传递用户输入的值 < li>运行将从另一个站点检索数据的脚本
- 将检索到的数据插入当前正在创建的节点上的字段
我不确定从哪里开始。规则模块看起来很有前途,因为我可以定义何时做某事,但我不知道如何调用脚本、发送数据或插入检索到的数据进入我创建的节点。
另一个想法是生成新节点的 XML 文件,以某种方式调用脚本,并让 Feeds 模块解析更新的 XML 文件(包含检索到的数据)以更新节点。
任何帮助将不胜感激。我在这个问题上不知所措!
最佳答案
您可以在自定义模块中使用 hook_node_presave() 来实现这一点。
在此示例中,您的模块名为 my_module
,您的自定义内容类型的 $node->type
为 custom_type
。
您发送给 python 脚本的节点字段名称是:field_baz
你的 python 脚本是:/path/to/my/python_script.py
它有一个参数,即 field_baz
通过返回 python 脚本填充的附加节点字段是 field_data_foo
和 field_data_bar
不清楚 python 脚本的输出是什么,所以这个例子模拟输出好像是一个 JSON 字符串。
该示例使用 hook_node_presave() 在保存之前操作 $node 对象。这是在节点数据写入数据库之前处理的。节点对象被视为引用,因此对该对象的任何修改都将在保存时使用。
逻辑检查 !isset($node->nid)
因为您提到这仅在创建节点时发生。如果它也需要在节点更新时发生,只需删除该条件即可。
/**
* Implements hook_node_presave().
*/
function my_module_node_presave($node) {
if ($node->type == 'custom_type' && !isset($node->nid)) {
// Get the user value from the node.
// You may have to clean it so it enters the script properly
$baz = $node->field_baz[LANGUAGE_NONE][0]['value'];
// Build the command string
$cmd = '/path/to/my/python_script.py ' . $baz;
// Execute the script and store the output in a variable
$py_output = shell_exec($cmd);
// Assuming the output is a JSON string.
$data = drupal_json_decode($py_output);
// Add the values to the fields
$node->field_data_foo[LANGUAGE_NONE][0]['value'] = $data['foo'];
$node->field_data_bar[LANGUAGE_NONE][0]['value'] = $data['bar'];
// Nothing more to do, the $node object is a reference and
// the object with its new data will be passed on to be saved.
}
}
关于python - 节点创建期间的 drupal 7 触发脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15254348/