All Products
Search
Document Center

Function Compute:Handlers

Last Updated:Apr 08, 2024

You can use Python handlers to respond to received events and execute the corresponding business logic. This topic describes the concepts and structure of Python handlers and provides examples.

What is a handler?

A handler of a function in Function Compute is the method used to process requests in function code. When a function is invoked, Function Compute uses the handler that you configure to process requests. You can configure a handler for a function by specifying the Handler parameter in the Function Compute console.

Handlers of Python functions in Function Compute follow the File name.Method name format. For example, if your file name is main.py and your method name is handler, the handler is main.handler.

For more information about the definitions and operations of functions in Function Compute, see Manage functions.

Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.

Handler signature

The following sample code shows a simple handler signature:

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

Parameter description:

  • handler: the name of the method to process requests. The method corresponds to the value that is specified for the Handler parameter in the Function Compute console. For example, if you set the handler for a Function Compute function to main.handler, Function Compute loads the handler method that is defined in main.py and executes the function from handler.

  • event: the parameter that is passed when you invoke the function. In the Python 2.7 runtime, the value of this parameter is of the string data type. In the Python 3 runtime, the value of this parameter is of the bytes data type.

  • context: the runtime context information that is provided when the Function Compute function is invoked.

Note

If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.

Example 1: Parse JSON-formatted parameters

Sample code

When you pass JSON-formatted parameters into functions in Function Compute, Function Compute passes through the parameters, and you need to parse the parameters in code. The following sample code provides an example on how to parse a JSON-formatted event.

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

Before you start

Create a function

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, select the Code tab. In the code editor, enter the preceding sample code and click Deploy.

    Important

    In the preceding sample code, the handler is the handler method in index.py. If the handler of your function is different, use the actual handler configurations.

  4. On the Code tab, click the down icon next to Test Function, click Configure Test Parameters from the drop-down list, enter the test parameters in the following sample code, and then click OK.

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

    After the function is executed, the execution result is returned. In this example, value is returned.

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

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'

In the preceding sample code, creds = context.credentials specifies to obtain the temporary AccessKey pair from context. This prevents hard encoding of sensitive information such as secrets.

Important

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

Before you start

Create a function

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, select the Code tab. In the code editor, enter the preceding sample code and click Deploy.

    Important

    In the preceding sample code, the handler is the handler method in index.py. If the handler of your function is different, use the actual handler configurations.

  4. On the Code tab, click the down icon next to Test Function, click Configure Test Parameters from the drop-down list, enter the test parameters in the following sample code, and then click OK.

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

    After the function is executed, the execution result is returned. In this example, success is returned.

Example 3: Call 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. Files in the current directory are returned. The following code shows an example:

import os
import subprocess

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

Example 4: Use an HTTP trigger to invoke a function

Sample code

For more information about formats of request payloads and response payloads of HTTP triggers, see Use an HTTP trigger to invoke a function.

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

def handler(event, context):
    logger = logging.getLogger()
    logger.info("receive event: %s", event)

    try:
        event_json = json.loads(event)
    except:
        return "The request did not come from an HTTP Trigger because the event is not a json string, event: {}".format(event)
    
    if "body" not in event_json:
        return "The request did not come from an HTTP Trigger because the event does not include the 'body' field, event: {}".format(event)
    req_body = event_json['body']
    if 'isBase64Encoded' in event_json and event_json['isBase64Encoded']:
        req_body = base64.b64decode(event_json['body']).decode("utf-8")

    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'text/plain'},
        'isBase64Encoded': False,
        'body': req_body
    }

Before you start

Use the preceding example to create a function in a Python runtime and configure a trigger. For more information, see Create a function and Create a trigger.

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Trigger tab to obtain the public endpoint of the HTTP trigger.

  4. Run the following command in Curl to invoke the function:

    curl -i "https://test-python-ipgrwr****.cn-shanghai.fcapp.run" -d 'Hello fc3.0'

    In the preceding command, https://test-python-ipgrwr****.cn-shanghai.fcapp.run is the obtained public endpoint of the HTTP trigger.

    Important
    • If the Authentication Method parameter of the HTTP trigger is set to No Authentication, you can use Postman or Curl to invoke the function. For more information, see Procedure.

    • If the Authentication Method parameter of the HTTP trigger is set to Signature Authentication or JWT Authentication, you can use the signature method or JWT authentication method to invoke the function. For more information, see Authentication.

    The following result is returned:

    HTTP/1.1 200 OK
    Content-Disposition: attachment
    Content-Length: 12
    Content-Type: application/json
    X-Fc-Request-Id: 1-64f7449a-127fbe39cd7681596e33ebad
    Date: Tue, 05 Sep 2023 15:09:14 GMT
    
    Hello fc3.0

Possible errors

This sample code can be called by using an HTTP trigger or a custom domain name. If you use an API operation but the configured test parameters do not comply with request format requirements of HTTP triggers, an error is reported.

For example, the following response is returned if you invoke the function by clicking Test Function in the Function Compute console after you configure the request parameters as "Hello, FC!".

The request did not come from an HTTP Trigger, event: "Hello, FC!"