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 ismain.handler
, the Function Compute will load thehandler
function defined in themain.py
and execute it from thehandler
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
Procedure
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.
Prerequisites
Procedure
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