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'| Parameter | Description |
|---|---|
handler | The 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. |
event | The 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). |
context | The 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
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the target service.
On the Functions page, click the name of the target function.
On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.
ImportantIn the sample code, the handler is the
handlermethod inindex.py. If your function uses a different handler configuration, update the code accordingly.On the Code tab, click the
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" }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:
| Field | Description |
|---|---|
access_key_id | Temporary AccessKey ID |
access_key_secret | Temporary AccessKey secret |
security_token | Security Token Service (STS) token—required when using oss2.StsAuth |
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:
OSS access permissions granted to the function's role via the RAM console
Test the function
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the target service.
On the Functions page, click the name of the target function.
On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.
ImportantIn the sample code, the handler is the
handlermethod inindex.py. If your function uses a different handler configuration, update the code accordingly.On the Code tab, click the
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" }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 retsubprocess.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.