All Products
Search
Document Center

Function Compute:Event handlers

Last Updated:Apr 01, 2026

This topic describes the event handler structure for Python functions in Function Compute and provides code examples for common scenarios: parsing JSON events, accessing OSS using temporary credentials, and running external commands.

Handler signature

All Python event handlers use the following signature:

def handler(event, context):
    return 'hello world'
ParameterDescription
handlerThe method that processes incoming requests. The name must match the Request Handler value configured in the Function Compute console. For example, if the request handler is set to main.handler, Function Compute loads main.py and calls the handler function defined in that file.
eventThe input passed when the function is invoked. In Python 2.7, the value is a str (STRING). In Python 3, the value is bytes (BYTES).
contextThe runtime context provided at invocation time. Use it to access temporary credentials and other runtime metadata.

Example 1: Parse a JSON event

Function Compute passes event data as raw bytes. Parse the payload with json.loads() before accessing individual fields.

# -*- coding: utf-8 -*-
import json

def handler(event, context):
    evt = json.loads(event)
    return evt['key']

Prerequisites

Before you begin, ensure that you have:

Test the function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the target service.

  3. On the Functions page, click the name of the target function.

  4. On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.

    Important

    In the sample code, the handler is the handler method in index.py. If your function uses a different handler configuration, update the code accordingly.

  5. On the Code tab, click the down icon next to Test Function, select Configure Test Parameters from the drop-down list, enter the following test input, and then click OK.

    {
      "key": "value"
    }
  6. Click Test Function.

The execution result is value.

Example 2: Access OSS using temporary credentials

Use the temporary credentials from context.credentials to access Object Storage Service (OSS). This avoids hardcoding sensitive information such as AccessKey pairs in your code.

import json
import oss2

def handler(event, context):
    evt = json.loads(event)
    creds = context.credentials
    # do not forget security_token
    auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
    bucket = oss2.Bucket(auth, evt['endpoint'], evt['bucket'])
    bucket.put_object(evt['objectName'], evt['message'])
    return 'success'

context.credentials provides three fields:

FieldDescription
access_key_idTemporary AccessKey ID
access_key_secretTemporary AccessKey secret
security_tokenSecurity Token Service (STS) token—required when using oss2.StsAuth
Important

The role assigned to the function must have permissions to access Object Storage Service (OSS). Grant permissions in the Resource Access Management (RAM) console.

Prerequisites

Before you begin, ensure that you have:

  • A function created

  • OSS access permissions granted to the function's role via the RAM console

Test the function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the target service.

  3. On the Functions page, click the name of the target function.

  4. On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.

    Important

    In the sample code, the handler is the handler method in index.py. If your function uses a different handler configuration, update the code accordingly.

  5. On the Code tab, click the down icon next to Test Function, select Configure Test Parameters from the drop-down list, enter the following test input, and then click OK.

    {
      "endpoint": "http://oss-cn-shenzhen-internal.aliyuncs.com",
      "bucket": "oss-********",
      "objectName": "oss-test-object",
      "message": "oss-test-content"
    }
  6. Click Test Function.

The execution result is success.

Example 3: Run external commands

Use Python's subprocess module to run Linux shell commands from your function. The following example runs ls -l and returns the directory listing.

import os
import subprocess

def handler(event, context):
    ret = subprocess.check_output(['ls', "-l"])
    return ret

subprocess.check_output() runs the command, waits for it to complete, and returns the output as bytes. If the command exits with a non-zero status, it raises a CalledProcessError.