You can use Python handlers to respond to received events and execute corresponding business logic. This topic describes concepts and structure of Python handlers and provides examples.
What is a handler?
A handler for a function in Function Compute is the method that is used to process requests in function code. When the function is invoked, Function Compute uses the handler that you configure to process requests. You can configure a handler for a function by using 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 functions in Function Compute and related operations, see Create an event function.
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. 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 tomain.handler
, Function Compute loads thehandler
method that is defined inmain.py
and executes the function fromhandler
.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.
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 an event that is in the JSON format.
# -*- coding: utf-8 -*-
import json
def handler(event, context):
evt = json.loads(event)
return evt['key']
Before you start
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.
ImportantIn the preceding sample code, the handler is the
handler
method inindex.py
. If the handler of your function is different, use the actual handler configurations.On the Code tab, click the 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" }
Click Test Function.
After the function is executed, the execution result is returned. The execution result in this example is
value
.
Example 2: Read and write OSS resources by using a temporary AccessKey pair
Python 3.12 sample code
In the Python 3.12 runtime, the credentials field in the context is removed. You can use the ALIBABA_CLOUD_ACCESS_KEY_ID
, ALIBABA_CLOUD_ACCESS_KEY_SECRET
, and ALIBABA_CLOUD_SECURITY_TOKEN
environment variables to access Object Storage Service (OSS). The following code snippet shows an example: For more information, see Obtain an AccessKey and AssumeRole.
import json
import oss2
def handler(event, context):
evt = json.loads(event)
auth = oss2.StsAuth(os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), os.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"))
bucket = oss2.Bucket(auth, evt['endpoint'], evt['bucket'])
bucket.put_object(evt['objectName'], evt['message'])
return 'success'
Python 3.10 sample code
You can use a temporary key pair that is provided by Function Compute to access Object Storage Service. The following code snippet provides an example:OSS
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 coding of sensitive information such as secrets.
Make sure that the configured role 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
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.
ImportantIn the preceding sample code, the handler is the
handler
method inindex.py
. If the handler of your function is different, use the actual handler configurations.On the Code tab, click the 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" }
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 sample 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. Configure an HTTP trigger for the function. For more information, see Create an event function and Configure an HTTP trigger that invokes a function with HTTP requests.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Triggers tab to obtain the public endpoint of the HTTP trigger.
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.ImportantIf 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, 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
The 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!"