Skip to content

Python Code

The Python Code component allows you to write and execute custom Python scripts directly within your Nappai workflow. It acts as a flexible bridge between visual automation blocks and the power of Python programming.

This component is ideal for tasks that standard visual nodes cannot handle, such as complex data transformation, custom logic calculations, or interacting with external APIs and AI models using code. You can use the Python environment to import libraries, process input data, and return results to continue your workflow.

How it Works

When you add this component to your dashboard, you are essentially creating a mini-execution environment for Python code. Here is how it functions internally:

  1. Code Execution: You write your Python script in the Python Code input field. When the workflow runs, Nappai takes this script and executes it in a secure, isolated Docker sandbox.
  2. Data Input: Any data connected to this component from previous steps is available inside your script via the variable data.
  3. Library Access: You can install and use any standard or third-party Python package (like pandas, requests, or openpyxl). These packages must be listed in the Packages input.
  4. Output Generation: The most critical part of this component is the return statement. Whatever you choose to return in your Python code becomes the output of this component, which can then be passed to the next step in your workflow. If you do not use return, the output will be empty.

Connection & Credentials

This component does not require specific credentials (such as API keys) to be configured in the Nappai panel. However, if your Python code needs to access external services (like sending emails or fetching data from a database), you should pass those credentials through Environment Variables or connect them via other components.

Inputs

The following fields are available to configure this component.

  • Input Data: The data that flows into this component from previous steps in your workflow. This is available in your Python script as the variable data. It can be a single item, a list, or a URL.
  • Python Code: The main input where you write your Python script.
    • Visible in: All operations
  • Packages: A list of Python packages to install before your code runs. Write one package name per line (e.g., requests, pandas==2.2.0).
    • Visible in: All operations
  • Python Version: Select the Python version for the execution environment (e.g., Python 3.9, 3.10).
    • Visible in: All operations
  • Tools: Connect external tools here to make them callable from within your Python code.
    • Visible in: All operations
  • Model: Connect an AI model to call it from within your Python code.
    • Visible in: All operations

Outputs

  • Processed Data: The result of your Python script execution. This is the value you explicitly return in your code.
  • Tool: If configured as a tool, this output provides the tool definition for external use.

Output Data Example (JSON)

When you use the return statement in your Python code, the data you return will be passed to the next component. Here is an example of a successful output after processing a list of items: json { “result”: { “status”: “success”, “message”: “Data processed successfully”, “items_count”: 5 } }

Connectivity

In a typical Nappai workflow, this component acts as a processor or transformer.

  • Input Connectivity: Connect the output of data-heavy components (like “Read CSV”, “Get Database Rows”, or “HTTP Request”) into the Input Data field of this component.
  • Output Connectivity: Connect the Processed Data output to subsequent components that need the transformed result. Common next steps include:
    • Write to Database: To save your processed results.
    • Send Email: To send a summary of the processed data.
    • Next Python Code: For further complex processing steps.

Usage Example

Scenario: You need to extract specific information from a raw text string and format it into a dictionary.

  1. Input: Connect a “Text Reader” component that outputs a raw string like "Name: John, Age: 30".

  2. Python Code: Write the following script in the Python Code field:

    # Input data is available as 'data'
    raw_text = data
    # Simple processing logic
    parts = raw_text.split(", ")
    name = parts[0].split(": ")[1]
    age = int(parts[1].split(": ")[1])
    # Return the formatted data
    return {
    "full_name": name,
    "age_years": age
    }
  3. Output: The Processed Data output will now contain:

    {
    "full_name": "John",
    "age_years": 30
    }

    You can then connect this output to another component that needs the structured data.

Important Notes

  • Return Statement is Mandatory: You must use the return keyword in your Python code to output data. If you do not return anything, the component’s output will be None, and subsequent components may fail or receive empty data.
  • Package Installation: When you add a new package to the Packages list, the first run might take a few seconds longer as Nappai installs the package. Subsequent runs will be faster because packages are cached.
  • Logging: You can use print() or log() in your code to debug. These outputs are sent to the Nappai Event Manager logs but do not affect the component’s final data output.
  • Security: The Python code runs in a sandboxed environment. Avoid using the component to perform sensitive system-level operations or accessing files outside the sandbox unless explicitly allowed by your system administrator.

Tips and Best Practices

  • Keep Code Simple: Try to keep your Python scripts short and focused. If your logic becomes too complex, consider breaking it down into multiple Python Code components.
  • Use Libraries Wisely: Use the Packages input to import only the libraries you need. This helps keep the execution time fast.
  • Handle Errors: In your Python code, use try/except blocks to handle potential errors gracefully. This prevents the entire workflow from crashing if a single step fails.
  • Debug with Print: If your component returns empty data, use print("Debug:", data) in your script and check the logs to see what the input actually looks like.

Security Considerations

  • Sandboxed Environment: The code runs in an isolated Docker container, preventing it from affecting the host system or other workflows.
  • No System Access: You cannot access the file system or network outside the sandbox unless explicitly configured.
  • Input Validation: Always validate the data input before processing to prevent unexpected errors or malicious input issues.