Introduction
You can extend the functionality of your Pabbly Connect workflow by using the popular programming language Python, with Code by Pabbly : Run Python action.Some of use cases include:
- Make an API request and manipulate the response as per need.
- Do some math operations on the dynamic values from the preceding steps in your workflow.
- Process your data in a way that you think is better than other apps onboard.
- Do your personalized processing or calculations which aren’t currently possible with other apps.
- Perform multiple tasks in a single step.
Warning - This step involves programming, so be careful! To use this, you probably need to be a coder, though you are welcome to play about with it. There is no technical help for errors in your code!
Note: The environment is Python 3.9. Your code can only run for a limited amount of time i.e. up to 25 seconds and within a limited amount of memory i.e. up to 128MB. If you exceed those limits - your script will be killed.
Section 1.
Variable and function declarations
Entire content you write in or enter into the Python Code field is internally wrapped in a function as shown below:
Python:
# imported modules:
import json
import math
import logging
import requests
# the wrapper function
def funcion_name():
# predefined variable
output=None
# named logger
logger = logging.getLogger('code')
# Your code:
... ... ...
... ... ...
# default return
return output
Key points
- Some frequently used popular modules, namely json, math, logging, and requests, have been already imported for your convenience.
- Note that the wrapper function has a predefined variable, output, and a named logger, labeled as 'code'.
- You can define your own set of variables by avoiding already defined identifiers.
Standard modules and built-in functions are available
Run Python action comes with some already imported modules, namely json, math, logging, and requests (as elaborated above). You don’t need to import these modules in your code again. You can import and use any other standard modules and use built-in functions which are not intended for either file system operations, or `exec` or `eval`.
For code examples, see out section 4 and section 5 of this guide.
You can check out our full list of available Python modules.
1.1. Unsupported operations
1.1.1. Run Python action is not for operations with the file system and functions like exec and eval.
If your code includes these operations, you’ll get an error message like “Please avoid file operations and functions like exec and eval.
”1.1.2. Avoid using if __name__ == "__main__"
Instead of nesting statements under logic if __name__ == "__main__"
, call those statements directly.Reason
A user’s code doesn’t run in the main thread. So, the expression__name__ == "__main__"
in a user’s code evaluates to False
. That means, your code block starting with if __name__ == "__main__":
won’t be executed.Example
The following code snippet has no result.
Python:
def yourFunction(arg):
print(arg)
if __name__ == "__main__":
yourFunction(“hello”)
Instead, directly call
yourFunction
as shown below. It gives you the expected result (prints “hello”).
Python:
def yourFunction(arg):
print(arg)
yourFunction(“hello”)
1.1.3. The characters <
and >
can't be used in the code input field directly.
Solution (workaround)
Escape<
and >
characters in the input texts. Escaping should be done using the corresponding ASCII hex code-point or Unicode code-point, as shown below.<
should be written as either\x3C
or\u003C
.>
should be written as either\x3E
or\u003E
.
Example
You can write<br>
as \x3Cbr\x3E
.Section 2.
Return a value: obtain the final output/result of the execution
The returned value will be available under the label Output in the step Response.You have two ways to return your required value. Follow any one of these —
- use a return statement,
- use the `output` variable instead of a return statement.
The `output` variable is returned by default if you set a value to it and don't use a return statement.
The above two ways are demonstrated below.
2.1. Using a return statement:
Python:
# Convert a given paragraph to uppercase and then extract sentences from it:-
para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.'
modification1 = para.upper()
modification2 = modification1.replace('. ', '.*')
sentences = modification2.split('*')
return sentences
2.2. Using the `output` variable instead of a return statement:
Assign your required value to our predefined variable
output
. The last assigned value of output
will be returned as your execution result.
Python:
# Convert a given paragraph to uppercase and then extract sentences from it:-
para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.'
modification1 = para.upper()
modification2 = modification1.replace('. ', '.*')
output = modification2.split('*')
Notice that the outcome (the step Response) is the same.
Section 3.
Logging: printing a variable for testing/debugging
Logging is optional. In order to check (print) intermediate values of the execution, you can use eitherprint()
function or the already named logger
(labeled as 'code').All the printings will be visible under the label Logs in the step Response.
Python:
# Convert a given paragraph to uppercase and then extract sentences from it:-
para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.'
modification1 = para.upper()
print(modification1) # print
modification2 = modification1.replace('. ', '.*')
sentences = modification2.split('*')
logger.info(sentences) # info
return sentences
Important:
Logging/printing option is not for obtaining the final output of the workflow step. You should always use return statements or output variable (as demonstrated in section 2 above) to obtain the result (final output) and use it in subsequent actions.
Section 4.
Frequently used modules
Some frequently used modules, namely json, math, logging, and requests, have been already imported by us, for your convenience. So, you don't need to import them again in your code.Here are some examples covering uses of these modules.
4.1. json
Here's an example of encoding a Python dictionary into JSON format:
Python:
my_dict = {"name": "John", "age": 30, "city": "New York"}
# Encoding the dictionary to JSON format
json_data = json.dumps(my_dict)
print(json_data)
4.2. math
The math library in Python provides various mathematical functions. Here's an example of how to use the sqrt() function to calculate the square root of a number:
Python:
x = 16
# Calculate the square root of x
y = math.sqrt(x)
return y
4.3. logging
As mentioned earlier, internally we've imported the logging module and defined a named
logger
for your convenience. We've named (labeled) the logger as 'code'. So, just directly call the logger
methods.
Python:
# Log some messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
4.4. requests
To easily make HTTP requests we have imported a third party module, namely requests. Here's an example of how to make a GET request:
Python:
response = requests.get('https://hub.dummyapis.com/products?noofRecords=10&idStarts=1001¤cy=usd')
response.raise_for_status()
def test():
return {'result': response.json()[0]}
return test()
Section 5.
Other Python Modules
- Our Python environment provides all the standard modules available in Python 3.9.
- Exceptions: We have blocked only three specific modules, namely `os`, `subprocess`, and `sys`.
- In addition to the standard modules, a popular third-party module, namely `requests`, is available for you.
- Internally we've imported four frequently used modules, namely json, math, logging, and requests. As elaborated above, you can directly use them without importing the same again. To use any of other modules, you'll have to import it first.
- You can check our full list of available Python modules.
5.1. Example: Importing modules
Python:
# Import required modules:
import datetime
import time
# Use modules:
current_date = datetime.date.today()
current_time = time.time()
current_date_time = time.strftime("%Y-%m-%d %H:%M:%S")
# Create a dictionary with the key-value pairs:
output = {
"current_date": str(current_date),
"current_time": current_time,
"current_date_time ": current_date_time
}
Attachments
-
1676894323257.png52.5 KB · Views: 574
-
1676895896240.png47.3 KB · Views: 490
-
1676896100990.png66.9 KB · Views: 482
-
1684052473235.png48.8 KB · Views: 343
-
image_2023-09-12_121251456.png94.4 KB · Views: 113
-
image_2023-09-12_184959225.png105.6 KB · Views: 109
-
1694526915333.png59.9 KB · Views: 123
-
workaround-1-1.png164.3 KB · Views: 125
Last edited by a moderator: