This topic describes the structure of event handlers in Python environments and provides examples of event handlers in Python.

Signatures for event handlers

The following sample code describes the signature for an event handler.

def handler(event, context):
    return 'hello world'

Parameter description:

  • handler: the name of the method that you use to process requests. The method corresponds to the value that is specified for the Request Handler parameter in the Function Compute console. For example, if the handler that is configured for a Function Compute function is main.handler, Function Compute loads the handler function that is defined in main.py and executes the function from the handler function.
  • event: the parameter that you pass when you invoke the function. In the Python 2.7 runtime environment, the value of this parameter is in the STRING type. In the Python 3 runtime environment, the value of this parameter is in the BYTES type.
  • context: the runtime context provided when the Function Compute function is invoked.

Example 1: Parse JSON-formatted parameters

Sample code

Function Compute passes through the JSON-formatted parameters that you configured, you must parse the parameters in the code. The following sample code provides an example on how to parse an event that is in the JSON format.

# -*- coding: utf-8 -*-
import json
def handler(event, context):
    evt = json.loads(event)
    return evt['key']

Prerequisites

Create a function

Procedure

  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 desired service.
  3. On the Functions page, click the name of the desired function.
  4. On the Function Details page, click the Code tab, enter the preceding sample code in the code editor, and then click Deploy.
    Important In the preceding sample code, the handler is the handler method in index.py. If the handler configurations of your function are different, use your actual handler configurations.
  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 parameters, and then click OK.
    {
      "key": "value"
    }
  6. Click Test Function.
    After the function is executed, the execution result is returned. The execution result is value.

Example 2: Read and write OSS resources by using a temporary AccessKey pair in a secure manner

Sample code

You can use a temporary key pair that is provided by Function Compute to access Object Storage Service (OSS). The following code is used as an example.

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'

You can obtain the temporary AccessKey pair from context in creds = context.credentials. This prevents hard encoding on sensitive information such as secrets.

Important Make sure that the role that is configured for the service has the permissions to access Object Storage Service (OSS). You can log on to the Resource Access Management (RAM) console and grant the role permissions to access OSS.

Prerequisites

Create a function

Procedure

  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 desired service.
  3. On the Functions page, click the name of the desired function.
  4. On the Function Details page, click the Code tab, enter the preceding sample code in the code editor, and then click Deploy.
    Important In the preceding sample code, the handler is the handler method in index.py. If the handler configurations of your function are different, use your actual handler configurations.
  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 parameters, 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.
    After the function is executed, the execution result is returned. The execution result is success.

Example 3: Run external commands

You can use a Python program to create a fork process to call external commands. For example, you can use the subprocess module to call the ls -l command in Linux. The files in the current directory are returned. The following sample code shows an example:

import os
import subprocess

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