This topic shows you how to perform operations by using Function Compute SDK for Python to call the required API operations with efficiency. For example, you can create functions and triggers, and invoke functions.

Prerequisites

Make sure that the following operations are completed:

Python SDK example

# -*- coding: utf-8 -*-

import fc2
import os

# Enter the temporary key, including the temporary token.
# The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
# We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
# In this example, the AccessKey pair is saved to the environment variables for authentication. 
# Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your local environment before you run the sample code. 
# In the runtime environments of Function Compute, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
client = fc2.Client(
    endpoint='<Your Endpoint>',
    accessKeyID=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    accessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'))

# Configure virtual private cloud (VPC) settings when you create the service. 
vpcConfig = {
    'vpcId': '<Your Vpc Id>',
    'vSwitchIds': ['<[Your VSwitch Ids]>'],
    'securityGroupId': '<Your Security Group Id>'
}

# Configure vpcConfig when you create the service. 
# Configure a role when you configure the VPC settings. 
vpc_role = 'acs:ram::12345678:role/aliyunvpcrole'

# Configure Apsara File Storage NAS (NAS) settings when you create the service. 
nasConfig = {
    "userId": '<The NAS file system user id>',
    "groupId": '<The NAS file system group id>',
    "mountPoints": [
        {
            "serverAddr" : '<The NAS file system mount target>',
            "mountDir" : '<The mount dir to the local file system>',
        }
    ],
}

service = client.create_service('service_name', role=vpc_role, vpcConfig=vpcConfig, nasConfig=nasConfig)

# Create an initializer function. 
# The current directory contains the main.zip package, in which the myhandler function is contained in the main.py file. 
# Configure the {'testKey': 'testValue'} environment variable. 
# main.my_initializer is the entry point of the initialization interface. 
client.create_function('service_name', 'function_name', 'python3',  'main.my_handler', "main.my_initializer", codeZipFile = 'main.zip', environmentVariables = {'testKey': 'testValue'})

# Synchronously invoke a function. 
client.invoke_function('service_name', 'function_name')

# Create a trigger. 
# Create an Object Storage Service (OSS) trigger. 
oss_trigger_config = {
    'events': ['oss:ObjectCreated:*'],
    'filter': {
        'key': {
            'prefix': 'prefix',
            'suffix': 'suffix'
        }
    }
}
source_arn = 'acs:oss:cn-shanghai:12345678:bucketName'
invocation_role = 'acs:ram::12345678:role/aliyunosseventnotificationrole'
client.create_trigger('service_name', 'function_name', 'trigger_name', 'oss',oss_trigger_config, source_arn, invocation_role)

# Create a Log Service trigger. 
log_trigger_config = {
    'sourceConfig': {
        'logstore': 'log_store_source'
    },
    'jobConfig': {
        'triggerInterval': 60,
        'maxRetryTime': 10
    },
    'functionParameter': {},
    'logConfig': {
        'project': 'log_project',
        'logstore': 'log_store'
    },
    'enable': False
}
source_arn = 'acs:log:cn-shanghai:12345678:project/log_project'
invocation_role = 'acs:ram::12345678:role/aliyunlogetlrole'
client.create_trigger('service_name', 'function_name', 'trigger_name', 'log',log_trigger_config, source_arn, invocation_role)
# Create a time trigger. 
time_trigger_config = {
    'payload': 'awesome-fc',
    'cronExpression': '0 5 * * * *',
    'enable': True
}
client.create_trigger('service_name', 'function_name', 'trigger_name', 'timer', time_trigger_config, '1', '')

# Invoke a function that contains input parameters. 
client.invoke_function('service_name', 'function_name', payload='hello_world')

# Read an image and invoke a function by using file data as the input parameters. 
src = open('src_image_file_path', 'rb') # Note: please open it as binary.
r = client.invoke_function('service_name', 'function_name', payload=src)

# Save the result as an output image. 
dst = open('dst_image_file_path', 'wb')
dst.write(r.data)
src.close()
dst.close()

# asynchronously invoke a function. 
client.invoke_function('service_name', 'function_name', headers = {'x-fc-invocation-type': 'Async'})

# Obtain services. 
client.list_services()

# Query functions that have a specific prefix and limit. 
client.list_functions('service_name', prefix='the_prefix', limit=10)

# Delete a trigger.
client.delete_trigger('service_name', 'function_name','trigger_name')

# Delete a function. 
client.delete_function('service_name', 'function_name')

# Delete a service. 
client.delete_service('service_name')