tencent cloud

$0 14-Day TrialExperience EdgeOne for acceleration and security protection!

Feedback

Serverless Cloud Function

SDK for Python

Last updated: 2024-12-02 19:27:44

Tencentserverless SDK Overview

Tencentserverless is a Tencent Cloud SCF SDK that integrates SCF business flow APIs to make it easier to invoke SCF functions. It allows users to invoke a function quickly from a local system, CVM instance, container or function, eliminating the need to encapsulate APIs in a public cloud.

Features

Tencentserverless SDK has the following features:
Invokes functions in a high-performance, low-latency manner.
Enables quick invocation across functions after the required parameters are entered (it will obtain parameters in environment variables by default, such as region and SecretId).
Supports access with private network domain names.
Supports session keep-alive.
Supports cross-region function chaining.
Supports native invocation methods in Python.
Note:
Calling SDK across functions is only applicable to event-triggered functions. HTTP-triggered functions can be invoked by requesting the corresponding path of the function in the function code.

Getting Started

Mutual function invocation

Samples

Note:
To make functions in different regions invoke each other, regions must be specified. For the naming convention, see Common Params.
If no region is specified, intra-region mutual function invocation will be used by default.
If no namespace is specified, default will be used by default.
1. Create an invoked Python function in the cloud named FuncInvoked in Guangzhou region with the following content:
# -*- coding: utf8 -*-

def main_handler(event, context):
if 'key1' in event.keys():
print("value1 = " + event['key1'])
if 'key2' in event.keys():
print("value2 = " + event['key2'])
return "Hello World from the function being invoked" #return

2. Create an invoking Python function in the cloud named PythonInvokeTest in Chengdu region. You can edit it as needed in the following two methods.
Method 1. If you don't need to invoke the function frequently, you can use the following sample code:
from tencentserverless import scf
from tencentserverless.scf import Client
from tencentserverless.exception import TencentServerlessSDKException
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

def main_handler(event, context):
print("prepare to invoke a function!")
try:
data = scf.invoke('FuncInvoked',region="ap-guangzhou",data={"a": "b"})
print (data)
except TencentServerlessSDKException as e:
print (e)
except TencentCloudSDKException as e:
print (e)
except Exception as e:
print (e)
return "Already invoked a function!" # return


The output is as follows:
"Already invoked a function!"
Method 2. If you need to invoke the function frequently, you can choose to connect and trigger it through Client by using the following sample code:
# -*- coding: utf8 -*-

from tencentserverless import scf
from tencentserverless.scf import Client
from tencentserverless.exception import TencentServerlessSDKException
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

def main_handler(event, context):
#scf = Client(region="ap-guangzhou") # To use this method to establish a `Client` connection, enable the "execution role" feature in the function configuration and select an execution role with the function invocation permission.
scf = Client(secret_id="AKIxxxxxxxxxxxxxxxxxxxxxxggB4Sa",secret_key="3vZzxxxxxxxxxxxaeTC",region="ap-guangzhou",token=" ")# To use this method to establish a `Client` connection, replace `secret_id` and `secret_key` in the sample code with your actual `secret_id` and `secret_key`. This key pair needs to contain the function invocation permission.
print("prepare to invoke a function!")
try:
data = scf.invoke('FuncInvoked',data={"a": "b"})
# data = scf.FuncInvoked(data={"a": "b"}) # To use Python's native invocation method, perform initialization through `Client` first.
print (data)
except TencentServerlessSDKException as e:
print (e)
except TencentCloudSDKException as e:
print (e)
except Exception as e:
print (e)
return "Already invoked a function!" # return

The output is as follows:
"Already invoked a function!"
Note:
secret_id and secret_key: TencentCloud API key ID and key, which can be obtained or created in TencentCloud API Key > API Key Management in the CAM console.

Local function invocation

Preparations for development

Development environment Python 2.7 or Python 3.6 has been installed.
Running environment Windows, Linux, or macOS with Tencentserverless SDK installed.
Note:
For local function invocation, you must complete the above preparations. We recommend you develop the function locally and then upload it to the cloud and use mutual function invocation for debugging.

Installation through pip (recommended)

Run the following command to install Tencentserverless SDK for Python.
pip install tencentserverless

Installation through source package

Go to GitHub to download the latest source package and install it by running the following commands after decompression.
cd tencent-serverless-python-master
python setup.py install

Configuring Tencentserverless SDK for Python

Run the following command to upgrade Tencentserverless SDK for Python.
pip install tencentserverless -U
Run the following command to view the information of Tencentserverless SDK for Python.
pip show tencentserverless

Samples

1. Create an invoked Python function in the cloud named FuncInvoked in Guangzhou region with the following content:
# -*- coding: utf8 -*-

def main_handler(event, context):
if 'key1' in event.keys():
print("value1 = " + event['key1'])
if 'key2' in event.keys():
print("value2 = " + event['key2'])
return "Hello World from the function being invoked" #return
2. Create a local file named PythonInvokeTest.py with the following content:
# -*- coding: utf8 -*-

from tencentserverless import scf
from tencentserverless.scf import Client
from tencentserverless.exception import TencentServerlessSDKException
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

def main_handler(event, context):
print("prepare to invoke a function!")
scf = Client(secret_id="AKIxxxxxxxxxxxxxxxxxxxxxxggB4Sa",secret_key="3vZzxxxxxxxxxxxaeTC",region="ap-guangzhou",token=" ")# Replace with your own `secret_id` and `secret_key`
try:
data = scf.invoke('FuncInvoked',data={"a":"b"})
# data = scf.FuncInvoked(data={"a":"b"})
print (data)
except TencentServerlessSDKException as e:
print (e)
except TencentCloudSDKException as e:
print (e)
except Exception as e:
print (e)
return "Already invoked a function!" # return

main_handler("","")


Go to the directory where the PythonInvokeTest.py file is located and run the following command to view the result.
python PythonInvokeTest.py
The output is as follows:
prepare to invoke a function!"Hello World form the function being invoked"

API List

API Reference

Client (class)
invoke (method)

Client

Method

__init__
Parameter information:
Parameter Name
Required
Type
Description
region
No
String
Region, which is the same as the region of the function invoking the API and is Guangzhou for local invocations by default.
secret_id
No
String
User `SecretId`, which is obtained from the function's environment variable by default and is required for local debugging.
secret_key
No
String
User `SecretKey`, which is obtained from the function's environment variable by default and is required for local debugging.
token
No
String
User `token`, which is obtained from the function's environment variable by default.

invoke
Parameter information:
Parameter Name
Required
Type
Description
function_name
Yes
String
Function name.
qualifier
No
String
Function version. Default value: $LATEST.
data
No
Object
Input parameter for function execution, which must be an object that can be processed by `json.dumps`.
namespace
No
String
Namespace. Default value: default.


invoke

This is used to invoke a function. Currently, only sync invocation is supported.
Parameter information:
Parameter
Required
Type
Description
region
No
String
Region, which is the same as the region of the function invoking the API and is Guangzhou for local invocations by default.
secret_id
No
String
User SecretId, which is obtained from the function's environment variable by default and is required for local debugging.
secret_key
No
String
User SecretKey, which is obtained from the function's environment variable by default and is required for local debugging.
token
No
String
User token, which is obtained from the function's environment variable by default.
function_name
Yes
String
Function name.
qualifier
No
String
Function version. Default value: $LATEST.
data
No
String
Input parameter for function execution, which must be an object that can be processed by json.dumps.
namespace
No
String
Namespace. Default value: default.


TencentserverlessSDKException

Attributes:
[code]
[message]
[request_id]
[response]
[stack_trace]
Methods and descriptions:
Method Name
Description
get_code
Returns error code
get_message
Returns error message
get_request_id
Returns RequestId
get_response
Returns response
get_stack_trace
Returns stack_trace
Contact Us

Contact our sales team or business advisors to help your business.

Technical Support

Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

7x24 Phone Support
Hong Kong, China
+852 800 906 020 (Toll Free)
United States
+1 844 606 0804 (Toll Free)
United Kingdom
+44 808 196 4551 (Toll Free)
Canada
+1 888 605 7930 (Toll Free)
Australia
+61 1300 986 386 (Toll Free)
EdgeOne hotline
+852 300 80699
More local hotlines coming soon