3

我正在使用自定义内容类型在 Drupal 7 中创建一个站点。在创建节点时,我需要以某种方式触发 python 脚本(由其他人开发)的执行,这将:

  • 从当前创建的节点传递用户输入的值
  • 运行将从另一个站点检索数据的脚本
  • 将检索到的数据插入到当前正在创建的节点上的字段中

我不知道从哪里开始。规则模块看起来很有希望,因为我可以定义何时做某事但我不知道如何调用脚本、发送数据或将检索到的数据插入到我创建的节点中。

另一个想法是生成新节点的 XML 文件,以某种方式调用脚本,并让 Feeds 模块解析更新的 XML 文件(包含检索到的数据)以更新节点。

任何帮助将不胜感激。我在我头上这个!

4

1 回答 1

1

您可以在自定义模块中使用 hook_node_presave() 来实现这一点。

在此示例中,您的模块已命名my_module,您的自定义内容类型$node->typecustom_type.

您发送到 python 脚本的节点字段名称是:field_baz

您的 python 脚本是:/path/to/my/python_script.py它需要一个参数,即field_baz

要由您的 python 脚本的返回填充的其他节点字段是field_data_foofield_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.
  }
}
于 2013-03-07T01:46:41.977 回答