Reputation: 43
I am creating a site in Drupal 7 with a custom content type. On node creation, I need to somehow trigger the execution of python script (developed by someone else) which will:
I'm not sure where to start. The Rules module looks promising, as I can define when to do something, but I don't know how to call the script, send the data, or insert the retrieved data into the node I've created.
Another idea was to generate an XML file of the new node, somehow call the script, and have the Feeds module parse an updated XML file (containing the retrieved data) to update the nodes.
Any help will be greatly appreciated. I'm in over my head on this one!
Upvotes: 3
Views: 806
Reputation: 13321
You can achieve this with hook_node_presave() in your custom module.
In this example, your module is named my_module
and your custom content type's $node->type
is custom_type
.
The node's field name you send to your python script is: field_baz
Your python script is: /path/to/my/python_script.py
and it takes one argument, which is the value of field_baz
The additional node fields to be populated by the return of your python script are field_data_foo
and field_data_bar
It wasn't clear what the output of the python script is, so this example simulates as if the output is a JSON string.
The example uses hook_node_presave() to manipulate the $node object before it is saved. This is processed before the node data is written to the database. The node object is treated as a reference, so any modifications to the object is what will be used when it is saved.
The logic checks that !isset($node->nid)
because you mentioned that this only happens when a node gets created. If it needs to happen when a node gets updated as well, just remove that condition.
/**
* 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.
}
}
Upvotes: 1