SDK for Python

Last updated: 2021-10-12 18:11:06

    Tencentserverless SDK Overview

    Tencentserverless is a Tencent Cloud SCF SDK that integrates SCF business flow APIs to simplify the function invocation method. It can be used to invoke a function quickly from a local system, CVM instance, container, or function, eliminating your need to encapsulate public TencentCloud APIs.

    Features

    Tencentserverless SDK has the following features:

    • It can invoke functions in a high-performance, low-latency manner.
    • It enables quick invocation across functions after the required parameters are entered (it will get parameters in environment variables by default, such as region and SecretId).
    • It supports access with private network domain names.
    • It supports session keep-alive.
    • It supports cross-region function invocation.
    • It supports Python's native invocation method.

    Getting Started

    Mutual function invocation

    Sample

    Note:

    • To make functions in different regions invoke each other, regions must be specified. For the naming convention, please see Region List.
    • 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 the 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
      
    1. Create an invoking Python function in the cloud named PythonInvokeTest in the 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 result 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 result 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
      Install Python 2.7 or Python 3.6.
    • Runtime environment
      Install Tencentserverless SDK, which supports Windows, Linux, and macOS.
    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
    

    Installing 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
    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
    

    Sample

    1. Create an invoked Python function in the cloud named FuncInvoked in the 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
      
    1. After the function is created, 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 `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 file directory of PythonInvokeTest.py, run the following command, and view the result.

    python PythonInvokeTest.py
    

    The output result is as follows:

    prepare to invoke a function!"Hello World form the function being invoked"
    

    API List

    API Reference

    Client

    Method:

    • __init__

      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.
    • invoke

      Parameter information:

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

    invoke

    This API is used to invoke a function. Currently, only sync invocation is supported.

    API 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, which is $LATEST by default.
    data No String Input parameter for function execution, which must be an object that can be processed by json.dumps.
    namespace No String Namespace, which is default by default.

    TencentserverlessSDKException

    Attribute:

    • [code]
    • [message]
    • [request_id]
    • [response]
    • [stack_trace]

    Method and description:

    Method 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