You can use a Python handler to process incoming events and run your business logic. This topic describes the concept and structure of Python handlers and provides examples.
What is a handler?
The handler of an FC function is the method in the function code that processes requests. When your FC function is invoked, Function Compute runs the handler that you provide to process the request. You can configure the handler in the Handler setting on the Function Compute console.
For Python FC functions, your handler is in the format filename.method_name. For example, if your file is named main.py and the method is named handler, the handler is main.handler.
For more information about creating FC functions, see Create an event-triggered 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 code shows a basic handler signature:
def handler(event, context):
return 'hello world'The handler signature includes the following parameters:
handler: The name of the method. This must match the handler you configure in the Function Compute console using the Handler setting. For example, if you set the handler for a FC tomain.handler, Function Compute loads thehandlermethod defined inmain.pyand executes thehandlerfunction.event: The parameter that contains the data passed to the function. In the Python 2.7 runtime, this is a string. In Python 3 runtimes, it is bytes.context: An object that provides FC information about the invocation.
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 a JSON-formatted event
Sample code
Function Compute passes the content of JSON-formatted events directly to your function. You must parse this content in your code. The following sample code shows how to parse a JSON-formatted event.
# -*- coding: utf-8 -*-
import json
def handler(event, context):
evt = json.loads(event)
return evt['key']Prerequisites
Create an event-triggered function
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 sample code and then click Deploy.
ImportantIn the sample code, the handler is the
handlermethod inindex.py. If your function's handler is configured differently, update the filename and method name accordingly.On the Code tab, click the arrow icon
next to Test Function and select Configure Test Parameters. Enter the following sample parameters, and then click OK.{ "key": "value" }Click Test Function.
After the function executes, the expected response is
value.
Example 2: Securely access OSS resources
Python 3.12 sample code
The Python 3.12 runtime removes the credentials field from the context. Instead, 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 shows an example. For more information, see Create an AccessKey and AssumeRole.
import json
import oss2
import os
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 the Function Compute provided by Object Storage Service to access OSS. The following code shows 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 sample code, creds = context.credentials retrieves the temporary AccessKey pair from the context object. This practice prevents you from hard-coding sensitive information, such as secrets, in your code.
Ensure that the role assigned to the service has permissions to access OSS. You can log on to the Resource Access Management (RAM) console to grant the required permissions to the role.
Prerequisites
Create an event-triggered function
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 sample code and then click Deploy.
ImportantIn the sample code, the handler is the
handlermethod inindex.py. If your function's handler is configured differently, update the filename and method name accordingly.On the Code tab, click the arrow icon
next to Test Function and select Configure Test Parameters. Enter the following sample parameters, 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 executes, the expected response is
success.
Example 3: Call an external command
Your Python function can also create a fork process to call external commands. For example, you can use the subprocess module to call the Linux command ls -l, which lists the files in the current directory. The following code shows an example.
import os
import subprocess
def handler(event, context):
ret = subprocess.check_output(['ls', "-l"])
return retExample 4: Invoke a function with an HTTP trigger
Sample code
For information about the request and response payload formats for HTTP trigger invocations, 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
}
Prerequisites
This example requires an HTTP-triggered function that is configured with a Python runtime and based on the sample code. For more information, see Create an event-triggered function and Configure an HTTP trigger.
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 find the public endpoint of the HTTP trigger.
Run the following curl command 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.runis the public endpoint of the HTTP trigger.ImportantIf the Authentication Method for the HTTP trigger is set to No Authentication, you can directly use a tool like Postman or curl to invoke the function. For more information, see the Procedure in this section.
If the Authentication Method is set to Signature Authentication, JWT Authentication, or Bearer Authentication, you must use the corresponding authentication method to invoke the function. For more information, see Authentication and authorization.
The following response 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 in this example is designed to be invoked by an HTTP trigger or a custom domain name. If you invoke the function through an API call and the test parameters do not conform to the HTTP trigger request format, an error occurs.
For example, in the Function Compute console, if you set the test event to "Hello, FC!" and click Test Function, the function returns the following response.
The request did not come from an HTTP Trigger, event: "Hello, FC!"