Python
Version 26.2.9623
Version 26.2.9623
Python
After you complete the prerequisites, CData Sync can read and execute Python anywhere that APIScript can be written.
To instruct the Sync scripting engine to use Python instead of APIScript, define Python as the scripting language by setting the language attribute on the sync:script keyword, as shown below:
<sync:script language="python">
# Python code goes here
</sync:script>
Python is embedded directly in the Sync scripting engine, which allows users who are familiar with Python to use a similar syntax to interact with messages and context within their scripts.
You can also use APIScript and Python in the same script. This approach is useful when you already have APIScript in place but you need to implement additional logic using Python. Python can access items directly that are defined in APIScript, as shown in this example:
<sync:set attr="CustomerA.OrderID" value="123456" />
<sync:script language="python">
print("The OrderId for CustomerA is", _ctx.CustomerA.OrderID)
</sync:script>
Several Python methods and variables are designed to work specifically with the message, item, and attribute context in Sync.
Built-in Object Interfaces
The Sync Python implementation provides two primary interfaces that expose the built-in variables listed below and enable access to scripting context.
-
SyncScriptContext
-
SyncScriptItem
SyncScriptContext
This interface represents the primary scripting context for Python scripts in Sync. It provides dictionary-like access to items and includes logging capabilities. The interface exposes the _ctx variable, which you use to access and manage the scripting context.
Available methods for this interface are as follows:
-
push -
log
SyncScriptItem
This interface represents individual data items in the Sync scripting environment. It provides dictionary-like access to attributes and maintains lists of values for each item. The following variables are pre-instantiated SyncScriptItem objects that are available automatically :
-
_input -
output
Available methods for this interface are as follows:
-
get -
clear
Understanding How SyncScriptContext and SyncScriptItem Work
The SyncScriptContext and SyncScriptItem interfaces work together to manage how data is accessed and processed within a script. The _ctx variable represents the overall scripting context and allows you to access or define items. You can use the syntax _ctx.itemname to create new items or access existing ones dynamically within the script.
The _input and output variables act as containers for data within the scripting context. The _input variable holds and exposes incoming data while the output variable holds and defines outgoing data.
Within this model, scripts typically read data from _input, use _ctx to access or organize items, and write results from output.
For more details, see Built-in Variables and Operations.
Built-in Variables
The built-in variables (_ctx, _input, and output) provide access to the core of the message context in a scripting environment. Use these variables to interact with the items that are available in the scripting engine.
_ctx
The _ctx variable is the primary way to access to the scripting environment. It provides access to all items that are available in the script and enables you to create new items, push items, and write entries to the application logs.
In the following example, the log method on the _ctx variable is used to write an entry to the application log at the INFO level:
<sync:script language="python">
...Python code...
_ctx.log('INFO', 'Successfully analyzed all data!')
... more Python code...
</sync:script>
_input
The _input variable represents the read-only input item of the scripting engine. The available attributes vary based on the context in which you are writing your event. For example, in an event that executes after a job, the following inputs are available:
-
ConnectorId -
WorkspaceId -
MessageId -
FilePath -
FileName -
Attachment# -
Header:*
However, if the event executes after an event, only outputs that are pushed from the previous events are available as inputs.
The following example prints the name of the connector to the log file of the current message:
<sync:script language="python">
...Python code...
print(_input.ConnectorId)
...more Python code...
</sync:script>
This example takes the input file, renames it, logs the original name, and then pushes the same file with a new name:
<sync:script language="python">
originalname = _input.Filename
print("The original filename was ", originalname)
output.Filename = "mynewfile.xml"
output.Filepath = _input.Filepath
</sync:script>
This example checks the name of the input file to determine whether it contains perishable or nonperishable items. Then, it sets a perishable header and value based on the file name:
<sync:script language="python">
# Check whether this is a perishable product list based on the filename
is_perishable = "perishables" in _input.FileName.lower()
# Set a perishable header and value based on the filename
output['Header:category'] = 'perishable' if is_perishable else 'non-perishable'
</sync:script>
output
The output variable is a built-in item that serves as an alternative to creating and pushing your own item when only a single output is needed. Unlike custom items that require you to explicitly call the push() method to send them as output, the output item is pushed automatically when the script completes. You just need to modify its properties and it is automatically pushed as output after the script execution is complete, without any additional push() calls needed.
You can set attributes directly on the item or define them by using a dictionary (dict), and you can do the same thing with items that you define yourself. The following example pushes an output file with some data:
<sync:script language="python">
output = {'data': 'This is a test',
'filename': 'foo.txt'}
</sync:script>
This next example takes the input file, renames it, logs the original name, then pushes the same file with a new name:
<sync:script language="python">
originalname = _input.Filename
print("The original filename was ", originalname)
output.Filename = "mynewfile.xml"
output.Filepath = _input.Filepath
</syncscript>
Operations
The following operations are available in the scripting environment to interact with the scripting context and items.
-
clear -
get -
log -
push
These operations allow you to log information, manage item output, and access or modify item attributes.
clear
The clear() operation clears the SyncScriptItem on which the method is called. The item remains the same, just empty.
<Sync:script language="python">
product = _ctx.product
product.name = 'Milk'
product.price = '2.99'
product.tags = ['perishable', 'dairy', 'noreturn']
print("Before clear:", product)
# Use the clear() method to remove all items
product.clear()
print("After clear:", product)
</Sync:script>
The previous example produces the following output:
Before clear: {"price":"2.99","name":"Milk","tags":["perishable","dairy","noreturn"]}
After clear: {}
get
The get(attr) operation returns the value of the specified attribute on the SyncScriptItem. This operation provides a programmatic way to access item attributes by name. It is functionally equivalent to accessing the attribute directly using dot notation (for example, _input.myattr) or using dictionary-style access (for example, _input.get('myattr')).
The following example prints the value list of the tags attribute on the item object to the log file of the current script:
<Sync:script language="python">
item = _ctx.item
item.name = 'Milk'
item.price = '2.99'
item.tags = ['perishable', 'dairy', 'noreturn']
print(item.get('tags'))
</Sync:script>
log
The log(level, message) operation, available on the _ctx variable, allows you to write entries directly to the Sync application log. The available log levels are DEBUG, INFO, WARNING and ERROR.
The following example uses the Python logging context to record an error-level message when data evaluation fails for a specific connector:
<Sync:script language="python">
...Python code...
_ctx.log('ERROR', f'Data evaluation failed in connector {_input.ConnectorId}!')
...more Python code...
</Sync:script>
push
The push(item) operation pushes the supplied item as output of the script. If no item is specified, the current output item is pushed.
In the following example, a new item (foo) is created in the SyncScriptContext, assigned some data and a filename, and then pushed out.
<Sync:script language="python">
foo = _ctx.foo
foo.Filename = "test2.txt"
foo.Data = "bar"
_ctx.push(foo)
</Sync:script>