This topic describes the structural features and examples of Python event request handlers.

Event Handler Signature

A simple Event Handler signature is defined as follows.

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

The example of Event Handler is parsed as follows:

  • handler: the name of the method. Corresponding to the request handler (function entry) configured in the Function Compute console. For example, if the handler configured for the FC function is main.handler, the Function Compute will load the handler function defined in the main.py and execute it from the handler function.
  • event: the parameter that you passed in when you called the function. In the Python 2.7 runtime environment, type String. In the Python 3 runtime environment, type Bytes.
  • context: Provides the runtime context information for your FC function call at the time of the call.

Example 1: Parse JSON-formatted parameters

Sample code

When you specify a JSON-formatted parameter, the Function Compute passes through the parameter content and requires you to parse it in the code. The following is a code example for parsing JSON-formatted events.

# -*- 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.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where your Kubernetes cluster is deployed.
  4. On the Functions page, click the name of the function that you want to manage.
  5. On the Function Details page, click the Function Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
  6. On the Function 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"
    }
  7. Click Test Function.
    After the function is successfully executed, view the returned result. You can see that the returned result is value.

Example 2: Securely read and write OSS resources by using a temporary key

Sample code

You can use the temporary key provided by the Function Compute to access the OSS, as shown in the following code 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'

The creds = context.credentials in the preceding code example indicates that the temporary key is obtained from the context parameters to avoid hard-coding sensitive information such as passwords in the code.

Notice Make sure that the role of the current service configuration has the permission to access the Object Storage Service (OSS). You can log on to the RAM console and grant permissions to the role to access Object Storage Service (OSS).

Prerequisites

Create a function

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where your Kubernetes cluster is deployed.
  4. On the Functions page, click the name of the function that you want to manage.
  5. On the Function Details page, click the Function Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
  6. On the Function 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.aliyuncs.com",
      "bucket": "oss-********",
      "objectName": "oss-test-object",
      "message": "oss-test-content"
    }
  7. Click Test Function.
    After the function is successfully executed, view the returned result. You can see that the returned result is success.

Example 3: Call an external command

Your Python program can also create fork processes and call external commands. For example, you can use the subprocess module to call ls -l commands in Linux to output a list of files in the current directory. Sample code:

import os
import subprocess

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