Python Script plugin can be found in Non-SAP Targets tab on the left panel of Designer Section. It passes the mapped import data to your Python script as JSON and returns the script result through its export fields.
Settings
No python installation is required.
This plugin uses IronPython that is an implementation of the Python programming language targeting the .NET Framework and Mono. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily.
The plugin embeds IronPython 2.7 (2.7.11). Scripts must use Python 2.7 syntax and semantics (for example, print is a statement unless you import it from __future__, and dict.items() returns a list). Packages that depend on CPython C extensions, such as numpy or pandas, cannot be used.
Available modules
The VeloXi Server and VeloXi Client installers unpack a pmodules folder into the installation directory. The plugin adds this folder to the module search path of every script. It contains:
- The Python 2.7 standard library (for example
json,csv,datetime,re,os,xml,email,sqlite3,urllib2,logging,unittest). - HTTP client libraries:
requestswith its dependencies (urllib3,chardet,idna,certifi). - Excel file libraries:
xlrd(read) andxlsxwriter(write). - XML helper:
xmltodict. - The IronPython
wpfandclrtypehelper modules.
Because the script runs on .NET, you can also load .NET assemblies with import clr and clr.AddReference(...), including VeloXi's own assemblies such as VeloXi.PManager (see Retrieving plugin settings). If the plugin was created from a template, the template folder is added to the search path as well, so libraries attached on the template's Libraries tab can be imported directly.
Click Settings on the plugin. The settings have three tabs: General, Transformations and Template.
- Description - short description that will be shown as plugin's name.
- LogLevel - level of detail written to the log.
- Notes - to write down any notes about the plugin.
- Editor - opens python scripts editor.
It is possible to:
- Blank - clear current Python script
- Open - open custom Python script
- Save - save current Python script
- Check - check whether script's code is valid or not
The editor also supports text search (Find and Replace, with Match case, Match whole word, Regular Expression and Wildcards options).
Other editor details:
- The editor has a Main Script tab. A second Structure tab appears when Use Smart Fields Creator is enabled (see Using Smart Fields Creator checkbox).
- Python syntax highlighting and line numbers are shown. Press Ctrl+Space to get a completion list of Python keywords, and Ctrl+F to open search.
- Open and Save work with
.pyfiles. The window title shows the file name and marks unsaved changes. The script itself is always stored inside the project, so the project does not depend on the file. - Check compiles and runs the top-level code of the script on the current tab in an isolated environment (imports, class and function definitions). It reports Ok, or the error message with the line number. It does not call your functions, so errors inside them appear only when the plugin runs.
- Ok applies the scripts to the plugin; Cancel closes the editor.
Architecture
Python Script plugin has Import and Export fields that can be added via Fields on the plugin.
- Import fields consist of several types of fields:
- String
- Int
- Float
- Bool
- Structure - equals to python dictionary data structure.
Can consist of String, Int, Float, Bool - Table - equals to python list data structure.
Can consist of String, Int, Float, Bool
- Export fields consist of the following types of fields:
- String
- Int
- Float
- Bool
- Table - equals to python list data structure.
Can consist of String, Int, Float, Bool - Structure - equals to python dictionary data structure.
Can consist of String, Int, Float, Bool
To add any field click Fields, enter its name and click Add or press Enter. Use Select All to show all fields on the canvas.
Also you can add fields with Smart Fields Creator.
You can change field's Data Type of the added field. Simply click on the field and pick needed type from dropdown list next to Data Type.
Every field in the 'Import' section has a 'Default Value' option that can be changed if the user clicks on the field. This allows the user to customize the value of the field to what they need in order to ensure the import data is accurate.
The "D" flag in the upper left corner of every field shows up if default value is used. This option is possible if you choose Ignore Source or Only If Source Empty.
Only If Source Empty is available when field is mapped and used only if imported data is empty
You can additionally mark Convert to Upper Case checkbox on String field to convert it to upper case.
Flag "U" will appear next to "D" flag.
Both Table and Structure fields can contain only String, Int, Float and Bool type of fields.
Script structure
Python plugin script gets data in serialized JSON string format based on import fields structure and must return data in serialized JSON string format according to export fields structure.
The main script must define a class named PyClass with a method dowork(self, kwargs). VeloXi creates one instance of the class and calls dowork once for every incoming request or record, passing all parameters in the kwargs dictionary. The default script created by Blank already has this shape:
import json
from collections import OrderedDict
class PyClass:
def __init__(self):
pass
def dowork(self, kwargs):
jobj = json.loads(kwargs['data'].decode('utf-8'), object_pairs_hook=OrderedDict)
# ... your logic ...
return json.dumps({'export_field': 'value'})
Projects created with early plugin versions may use an older dowork signature with six separate arguments instead of kwargs. The plugin still runs such scripts, but new parameters (such as log, username and password) are passed only to the kwargs form.
Import data (data)
kwargs['data'] is a JSON object whose keys are the import field names:
- Simple fields become JSON values, Structure fields become JSON objects, and Table fields become JSON arrays of objects (one object per source row).
- Only fields that are visible on the canvas and are either mapped or set to Ignore Source are included. Other import fields are not passed at all, so use
jobj.get('field')if a field may be missing. - Values are converted to the field's data type. Int and Float values that cannot be parsed, and Bool values other than
true/false, are passed asnull(Nonein Python). Numbers are parsed with an invariant culture (decimal point.). - Convert to Upper Case and the default value options are applied before the data is passed.
Field descriptions (input_fields, output_fields)
input_fields and output_fields are JSON objects keyed by field name. Each entry contains name, descr, tooltip, type (string, int, float, bool, structure or table), id, vis, attr (attribute name to selected flag), opts (option name to value) and fields (the child fields of a structure or table, otherwise null). Use them when the script needs the attributes or options you defined on the fields.
settings is a JSON object that maps each smart field name to its current value (buttons and separators are not included).
:param kwargs: dictionary of parameters. See below:
:Keyword Arguments:
* data -- Serialized JSON string with import data (`str`)
* settings -- Serialized JSON string with smart field values (`str`)
* input_fields -- Serialized JSON string with plugin import fields structure (`str`)
* output_fields -- Serialized JSON string with plugin export fields structure (`str`)
* environment -- Template path, may be None (`str`)
* id -- Plugin id (`str`)
* descr -- Plugin description (`str`)
* username -- User name received by the server plugin (`str`)
* password -- Password received by the server plugin (`str`)
* TransformationCommand -- Transformation rules script (`str`)
Only present if data transformation is used.
It can be called via exec() built-in function:
# exec(kwargs['TransformationCommand'])
# return json.dumps(jobj_out)
* log -- .NET logger object
Has method Write(...) that writes string version of given object in a log file
Arguments:
: Python object
: Optional bool arg
If True, string version of Object is written as required data
Example: log.Write(kwargs['id'])
Returning JSON
Here is an example of returning Table "table_field" with String field "string_field"
You can find examples in plugin by default.
:return Serialized JSON string is expected
Example:
table = [
{
"string_field": "value1"
},
{
"string_field": "value2"
}
]
return json.dumps({'table_field': table})
How the returned JSON is read:
- The result must be a JSON object (a Python
dictserialized withjson.dumps). Any other result causes an error. - Keys are matched to export field names without regard to case. Keys that do not match an export field are ignored.
- An export field that is missing from the result, or set to
None, returns an empty (null) value to the following plugins. - Values are converted to the export field's data type. A Structure must be a JSON object and a Table must be a list of JSON objects.
- Date strings are not converted; they are passed on exactly as returned.
Using Smart Fields Creator checkbox
It is possible to add several types of variables that will trigger dynamic structure building.
- Open the plugin Settings and go to the General tab.
- Set checkbox Use Smart Fields Creator.
- Select smart field type:
- *String -*e.g. Table name in SQL Database to pass it to the python script and then retrieve the structure.
- *Password -*uses Password Manager built-in tool.
- Directory Path - path to file directory.
- *File Name -*e.g. CSV file to parse it into plugins structure
- Button - smart button to call the plugin structure code.
- *ComboBox -*dropdown list.
- Separator - field structure separator.
Fill smart field name.
Select smart field action type (action type depends on field type):
- None - default type, structural script not called.
- Changed - calling a structural script when changing the value of a smart field.
- Changed\WPF - calling a structural script and WPF windows (if they are present) when changing the value of a smart field.
- Click - calling a structural script on button click.
- Click\WPF - calling a structural script and WPF windows (if they are present) on button click.
- Press Add button to add the smart field.
- Add or change the value of the smart field.
When Use Smart Fields Creator checkbox is enabled go to Editor and you will find that there is one more Python script available on the Structure tab
The structure script also defines PyClass. Which method is called depends on the smart field:
- A Button calls
<ButtonName>ButtonClick(self, kwargs), where spaces in the button name are replaced with underscores. The method is added to the structure script automatically when you add the button. - Any other smart field calls
DefaultValueChanged(self, kwargs)when its value changes.
The default structure script implements both by calling a shared getParameters method. The structure script runs in the Designer, not on the server. Action types without \WPF run the script in the background; the \WPF variants run it on the Designer's UI thread, which is required if the script opens WPF windows or message boxes.
Retrieving plugin settings
#Pre-requisites:
import json
#Password manager:
import clr
clr.AddReference('VeloXi.PManager')
from VeloXi.PManager import PasswordManager
#:param kwargs: dictionary of parameters. See below:
#:Keyword Arguments:
* settings -- Serialized JSON string with smart field values (`str`)
# Password Manager usage example:
# pm_object = PasswordManager.GetCredentials(json.loads(kwargs['settings'])['PM_SETTING_KEY'])
# user = pm_object.User
# password = pm_object.Password
# option = pm_object.Options['PM_OPTION_KEY']
* input_fields -- Serialized JSON string with plugin import fields structure (`str`)
* output_fields -- Serialized JSON string with plugin export fields structure (`str`)
* environment -- Template path, may be None (`str`)
* id -- Plugin id (`str`)
Building export and import structures
Go to Structure script.
To build a structure you need to return JSON serialized string in the following format:
#:return Serialized JSON string:
JSON keys that are expected:
* descr - Plugin Description (`str`)
* upper_descr - Plugin upper description (displayed on the right pane) (`str`)
* lower_descr - Plugin lower description (displayed on the right pane) (`str`)
* export - Plugin export structure (`dict`)
* fields - List of field objects (`list`) - see Field properties
* structures - List of structures (`list`)
* name - Structure name (`str`)
* fields - List of field objects (`list`)
* vis - Structure visibility (`bool`)
* tables - List of tables (`list`) - see Field properties
* name - Table name (`str`)
* fields - List of field objects (`list`)
* vis - Table visibility (`bool`)
* import - Plugin import structure (`dict`)
* fields - List of field objects (`list`) - see Field properties
* structures - List of structures (`list`)
* tables - List of tables (`list`)
* return - Optional result message (`dict`)
* type - 'i' (information) or 'e' (error) (`str`)
* message - Text shown to the user (`str`)
If return has a message, it is shown in a message box. If its type is e, the structure is not changed. If import or export is omitted, the existing fields in that section are left as they are. The plugin validates the returned JSON and lists any problems (for example, a structure without name) instead of building the fields.
Field properties:
## Field properties:
* descr - Field description (`str`) - mandatory
* dv - Default value (`str`)
* name - Field name (`str`)
* tooltip - Field ToolTip (`str`)
* type - Field type (string, int, float, bool) (`str`) - mandatory
* vis - Field visibility (`bool`)
* attr - List of attributes (`list`)
* name - Attribute name (`str`) - mandatory
* char - Attribute character (`str`) - mandatory
* color - Attribute color (blue, green, red, yellow) (`str`) - mandatory
* selected - Flag defines whether this attribute is checked or not (`bool`)
* tooltip - Attribute ToolTip (`str`)
* opts - List of options (`list`)
* name - Option name (`str`) - mandatory
* char - Option character. Displayed in the circle if not empty (`str`)
* color - Option color (blue, green, red, yellow) (`str`)
* tooltip - Option ToolTip (`str`)
* editable - Flag defines whether option is editable or not (`bool`)
* vis - Option visibility (`bool`)
* value - Option value (`str`)
Every field in fields list has several parameters:
- descr - Displayed by default on the canvas
- dv - Field's default value set by user
- name - Displayed if description is empty
- tooltip - Displayed on mouse hover
- type - Field type (string, int, float, bool)
- vis - Controls whether field is visible on the canvas once built
List of field attributes attr has:
- name - name of the flag
- char - Character that represents this field. Will be shown in the upper left corner of the field.
- color - Color of the flag
- selected - Is flag selected or not
Example:
f_attr = {
'name' : "Key",
'char': 'K',
'color' : 'blue',
'selected': True
}
field = {
'type': 'string',
'name': 'export_field',
'vis' : True,
'dv': 'Default value',
'attr': [f_attr]
}
Data transformation
The Transformations tab is used to create transformation rules without writing the whole script yourself.
- Select Use Data Transformation.
- Click Rules to define the rules. The number of defined rules is shown next to the button.
- Click Editor to view or change the generated transformation script.
At run time the rules script is passed to the main script as kwargs['TransformationCommand'] (see Script structure).
Creating plugin template
Open the Template tab in the Python plugin settings.
Click Create Template button
- New windows with settings will appear
- You are able to define PluginName, Description, Url, Version and GroupName of the plugin's template.
Is Closed - hides all source code on the plugin.
Remove All Fields - cleans plugin structure.
You can add custom notes in Notes tab .
You can attach custom libraries in the Libraries tab. Use Add File or Add Directory under Server Attachment and Client Attachment.
Click Save to save the plugin. You will be asked to add this template in the plugins section. Click Yes if you want to use it on current device or No if you just want to export the plugin for the further importing.
To save changes back to the template the plugin was created from, click Update Template on the Template tab.
Run-time behavior
- When the project starts on the server, the plugin compiles the main script and creates one
PyClassinstance. A script that fails to compile stops the project from starting, and the error is shown as the project status. The instance is discarded when the project stops, so changes to the script take effect after the project is restarted. - The same instance is reused for every call while the project runs. Values stored on
selfor at module level persist between calls. - Calls to Python Script plugins are serialized: on one server, only one
doworkcall runs at a time, even when several requests arrive in parallel. Keep long-running work (for example, slow HTTP calls) in mind when you design a project. usernameandpasswordcontain the credentials received by the server plugin of the project for the current request, if any.
Error handling
If the script raises an exception, or returns something that is not a JSON object, the plugin writes the Python error message and stack trace to the log and the call fails. The error is passed to the server plugin of the project, which reports it to the caller in its own way. To report a business error without failing the call, return it in an export field instead (the default script shows a return table with type, number, message and Detail fields for this purpose).
Test mode
The plugin has no separate test or simulation mode: the script always runs as written. If the script changes data in other systems, add your own test switch, for example a smart field value read from settings.
Log
Each call writes one entry to the plugin's client log. The method name is PythonScript followed by the plugin description (or the function name). The level of detail depends on LogLevel:
| LogLevel | Content |
|---|---|
| None | No detail log. |
| Short | Start and end time of the call, messages written with log.Write(value, True), and errors. |
| Full | Everything in Short, plus the class and function name, the import JSON, the returned export JSON, and messages written with log.Write(value). |
For plugins created from a closed template (Is Closed), the class and function name are not logged. Logs can be viewed in the Log section.
print output is not written to the log. Use kwargs['log'].Write(...) instead.
Prerequisites
- No separate Python installation. The IronPython runtime is part of the plugin, and the
pmoduleslibrary folder is installed with VeloXi Server and VeloXi Client. - Additional pure-Python libraries must be available on the server, for example by attaching them to a plugin template (Libraries tab, Server Attachment). Libraries used by the structure script must be available on the client (Client Attachment).
- Credentials used by the script should be stored in the Password Manager and selected with a Password smart field.
Limitations
- Python 2.7 language level (IronPython); CPython C-extension packages are not supported.
- Import and export fields support the types String, Int, Float, Bool, Structure and Table. Structures and tables cannot be nested.
- Import data and results are exchanged as JSON strings, so very large tables increase memory use and processing time.