Python backend code
Using Python
The Python Code Step allows you to write Python code that will be run on the backend. The common use cases for the Python Step are transforming and mapping of the data, as well as execution of machine learning-related functions.
You can use a number of pre-installed libraries to utilize their functionality within your code:
Variables in the code
If you want to use app variables in the Python code step, you must add them to the Variables section and NOT use directly in the code.
There, you can pass values from UI components using {{ui.input.value}}
. And you can also use some predefined variables to access the result of the previous step or to get user-related information.
While data
and error
are specific to a particular step, params
is available in all steps.
Merging results of multiple steps
In some cases, you may need to merge the results of multiple steps into a single object. This must also be done using the Variables section - pass this information to Python and access the output of any previous step using {{steps.<step_name>.data}}
.
Editor hotkeys
Ctrl + Enter/Cmd + Enter
- run the actionCtrl + F/Cmd + F
- find in codeCtrl + G/Cmd + G
- next find resultShift + Ctrl + F/Cmd + Option + F
- find and replace in the queryCtrl + L/Cmd + L
- jump to lineCtrl + Alt + L/Cmd + Option + L
- format code
Import external modules
To import external libraries, such as NumPy or Pandas, you can use the import
statement in your Python code. These libraries provide a wide range of useful functions and tools for data manipulation and analysis.
Here's an example of how to import NumPy:
Similarly, here's an example of how to import Pandas:
Data transformation
If the API returns its data in a different format than the components expect, you can use the Code Step to transform it. Python offers several built-in methods for transforming data, such as map(),
filter()
, and reduce()
.
For example, to add a new key to a list of dictionaries you can use the following code:
This creates a new list of dictionaries with an additional key is_adult
that is True if the age key is greater than or equal to 18. You can also use functions from external libraries such as NumPy and Pandas for more complex transformations.
Debugging errors
In case the code is failing or produces unexpected results:
Make sure no linter errors are present in the code (exclamation mark in the left gutter);
Check the result of the previous step (the
data
variable) and of the other variables (for example,params
);Comment out the code and add
return data
to see if the data is in the expected format;Use
print
to print the data to the console (Logs tab at the bottom of the action).
Last updated
Was this helpful?