Pandastack Documentation
  • Welcome
  • Getting Started
    • Quickstart
      • Getting Started
    • Projects
      • Static Website
        • Configure your static website
          • Pre-defined ENV for static websites
      • Conatinered Website
        • How to configure nodejs project
        • How to Configure Python projects
        • How to Configure GO project
        • Docker runtime Projects
        • Private Connection with database.
        • Override default ENV
    • Databases
      • MySQL
      • PostgreSQL
      • Redis
      • MongoDB
      • TimeScaleDB
    • Monitoring
      • Uptime Check
      • SSL monitoring
      • Monitors pricing
    • Analytics
    • SSO
      • Google
      • Azure
    • Managed Apps
      • Wordpres
      • Directus
      • Strapi
      • Consul
      • Jenkins
    • PandaEdge
      • Deploy a nodejs function
      • Deploy a python function
      • Panda Edge pricing
Powered by GitBook
On this page
  • Prerequisites
  • Supported Python Versions
  • Deployment Steps
  • 1. Create a New Function
  • 2. Function Naming
  • 3. Write Your Function
  • 4. Configure Function
  • 5. Manage Dependencies
  • Version Management
  • 1. Version History
  • 2. Rollback Capability
  • Testing Features
  • 1. Basic Testing
  • 2. Test Cases
  • 3. Debugging
  • 4. Mock Data Generation
  • Function Examples
  • 1. Data Processing Function
  • 2. Version-Aware Function
  • Best Practices
  • 1. Version Control
  • 2. Error Handling
  • 3. Resource Management
  • 4. Security
  • Troubleshooting
  • 1. Common Issues
  • 2. Performance Optimization
  1. Getting Started
  2. PandaEdge

Deploy a python function

This guide walks you through deploying, testing, monitoring, and managing a Python function on PandaEdge.

Prerequisites

  • A PandaEdge account

  • Basic knowledge of Python

  • Your function code ready for deployment

  • Appropriate access role (Owner or Admin for deployment)

Supported Python Versions

  • Python 3

  • Python 3.9 (Default)

Deployment Steps

1. Create a New Function

  1. Navigate to the Edge Functions dashboard

  2. Click "Create New" button

  3. Select "Python" as your runtime

  4. Choose your preferred Python version

2. Function Naming

Ensure your function name is:

  • 4-12 characters long

  • Contains only lowercase letters, numbers, and hyphens

  • Unique within your organization

3. Write Your Function

Basic function template:

import json
from datetime import datetime

def main(params):
    """
    Edge Function Handler
    Args:
        params: Parameters passed to the function
    Returns:
        dict: Response object
    """
    # Log the received parameters
    print('Received params:', json.dumps(params))

    # Your business logic here
    result = {
        'message': 'Hello from Python!',
        'timestamp': datetime.now().isoformat(),
        'params': params
    }

    # Return the response
    return {
        'statusCode': 200,
        'body': result
    }

4. Configure Function

{
    "name": "my-function",    # 4-12 characters, lowercase letters, numbers, hyphens
    "runtime": "python:3.9",  # Your selected Python version
    "memory": 256,           # Memory allocation in MB (128-1024)
    "timeout": 30            # Timeout in seconds (1-300)
}

5. Manage Dependencies

Create requirements.txt:

requests==2.28.1
pandas==1.4.2
numpy==1.22.3

Version Management

1. Version History

  • View all deployed versions

  • See deployment timestamps

  • Track authors and changes

  • Compare version performance

2. Rollback Capability

  • Roll back to any previous version

  • Instant version switching

  • No downtime during rollback

  • Automatic version tracking

Testing Features

1. Basic Testing

Use the built-in test interface to:

  • Send test requests

  • View responses

  • Check execution time

  • Monitor memory usage

2. Test Cases

Create reusable test cases:

# Test case configuration
{
    "name": "Data Processing Test",
    "path": "/api/process",
    "method": "post",
    "params": {
        "data": [1, 2, 3, 4, 5],
        "operation": "sum"
    },
    "expectedResult": {
        "statusCode": 200,
        "body": {
            "result": 15
        }
    }
}

3. Debugging

  1. Set breakpoints in your code

  2. Inspect variables during execution

  3. View call stack

  4. Step through code execution

4. Mock Data Generation

Generate test data for:

  • Strings

  • Numbers

  • Booleans

  • Arrays

  • Objects

Function Examples

1. Data Processing Function

import pandas as pd
import numpy as np

def main(params):
    try:
        # Validate input
        if 'data' not in params or not isinstance(params['data'], list):
            return {
                'statusCode': 400,
                'body': {
                    'error': 'Invalid input: data array required'
                }
            }
        
        # Convert to DataFrame
        df = pd.DataFrame(params['data'])
        
        # Calculate statistics
        stats = {
            'mean': float(df['value'].mean()),
            'median': float(df['value'].median()),
            'std': float(df['value'].std()),
            'count': len(df)
        }
        
        return {
            'statusCode': 200,
            'body': stats
        }
    except Exception as e:
        logging.error('Processing failed: %s', str(e))
        return {
            'statusCode': 500,
            'body': {
                'error': str(e)
            }
        }

2. Version-Aware Function

import os
from datetime import datetime

def main(params):
    # Get function version from environment
    version = os.environ.get('FUNCTION_VERSION', '1.0.0')
    
    print(f'Executing function version: {version}')
    
    try:
        # Version-specific logic
        result = handle_v2_request(params) if version.startswith('2') else handle_v1_request(params)
            
        return {
            'statusCode': 200,
            'body': {
                'version': version,
                'result': result,
                'timestamp': datetime.now().isoformat()
            }
        }
    except Exception as e:
        print(f'Error in version {version}: {str(e)}')
        return {
            'statusCode': 500,
            'body': {
                'error': str(e),
                'version': version
            }
        }

Best Practices

1. Version Control

  • Tag versions meaningfully

  • Document changes

  • Test before rollback

  • Monitor version performance

  • Keep deployment history

2. Error Handling

def main(params):
    try:
        # Your code here
        pass
    except Exception as e:
        logging.error('Function failed: %s', str(e))
        return {
            'statusCode': 500,
            'body': {
                'error': str(e),
                'version': os.environ.get('FUNCTION_VERSION', '1.0.0')
            }
        }

3. Resource Management

  • Use appropriate memory allocation

  • Set reasonable timeouts

  • Clean up resources

  • Use context managers for file/network operations

4. Security

  • Validate input data

  • Sanitize output

  • Use environment variables for secrets

  • Implement proper authentication

Troubleshooting

1. Common Issues

  1. Memory Issues

    • Monitor memory usage

    • Use generators for large datasets

    • Clean up resources

    • Increase memory allocation if needed

  2. Version Issues

    • Check version history

    • Verify deployment logs

    • Test previous versions

    • Monitor version metrics

  3. Dependency Issues

    • Verify package versions

    • Check compatibility

    • Update requirements.txt

    • Review package size

2. Performance Optimization

  1. Code Optimization

    • Use appropriate data structures

    • Implement caching when possible

    • Optimize database queries

    • Minimize external calls

  2. Resource Management

    • Monitor memory usage

    • Clean up resources

    • Use connection pooling

    • Implement proper error handling

PreviousDeploy a nodejs functionNextPanda Edge pricing

Last updated 3 months ago