Using Code Node
The Code Node allows you to write custom Python code to process data, transform information, and create custom logic in your workflows.
What is a Code Node?
A Code Node is a powerful node that executes Python code directly in your browser using Pyodide. It gives you the flexibility to write custom logic, process data, and integrate with connected database nodes.
Python Execution
Write and execute Python code directly in the browser. No server required.
Database Integration
Access connected database rows and columns through the db object.
Basic Structure
All Code Node scripts must define a process function that takes an optional input parameter:
def process(input=None):
# Your code here
return resultExamples
Example 1: Hello World
def process(input=None):
# Hello World example
print("Hello, World!")
return "Hello, World!"Example 2: Processing Database Rows with Date Calculation
This example iterates through database rows and creates a list of tuples with row IDs and dates incremented by 15 minutes:
import datetime
def process(input=None):
li = []
start_date = datetime.datetime.now()
for idx, ri in enumerate(db.rows):
next_date = start_date + datetime.timedelta(minutes=15*idx)
li.append((ri.id, next_date))
return liExplanation:
- Imports the
datetimemodule for date/time operations - Creates an empty list
lito store results - Gets the current date/time as
start_date - Iterates through
db.rowswith enumeration to get both index and row - Calculates
next_dateby adding 15 minutes multiplied by the index - Appends a tuple
(row_id, calculated_date)to the result list - Returns the list of tuples
Example 3: Filtering and Transforming Data
def process(input=None):
# Filter rows where a specific column meets a condition
filtered = [row for row in db.rows if row.status == 'active']
# Transform data
result = [{'id': row.id, 'name': row.name.upper()} for row in filtered]
return resultExample 4: Processing Input Data
def process(input=None):
if input is None:
return "No input provided"
# Process the input
if isinstance(input, str):
return input.upper()
elif isinstance(input, (int, float)):
return input * 2
else:
return str(input)Database Access
When a Code Node is connected to a Database Node, you can access the database data through the db object:
Available Properties
db.rows- List of Row objects, each with attributes for column valuesdb.columns- List of column definitions
Row Object Structure
Each row in db.rows has:
id- The row ID- Other attributes matching column names (e.g.,
row.name,row.email) to_dict()method to convert to a dictionary
Example usage:
for row in db.rows:
print(f"Row ID: {row.id}")
print(f"Name: {row.name}")
# Access any column as an attribute
print(f"Data: {row.to_dict()})Best Practices
Always define process function: This is required for code execution
Handle None input: Check if input is None before processing
Use type checking: Verify input types before operations
Return meaningful results: Return data that can be used by other nodes
Error handling: Use try/except for robust error handling
Database access: Check if db.rows exists before iterating
Troubleshooting
Common Issues
- "db is not defined": Make sure the Code Node is connected to a Database Node
- "AttributeError": Check that the column name exists in your database
- "SyntaxError": Verify your Python syntax is correct
- "Module not found": Some Python modules may not be available in Pyodide
Debugging Tips
- Use
print()statements to debug your code - Check the output panel for execution results
- Verify database connection status in the node configuration
- Test with simple code first, then add complexity
