Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ FunctionGraph/ Developer Guide/ Python/ Developing an Event Function

Developing an Event Function

Updated on 2024-11-11 GMT+08:00

Function Syntax

NOTE:

You are advised to use Python 3.6.

FunctionGraph supports Python 2.7, Python 3.6, Python 3.9, and Python 3.10.

Syntax for creating a handler function in Python:

def handler (event, context)

  • handler: name of the function that FunctionGraph invokes to execute your code. The name must be consistent with that you define when creating a function.
  • event: event parameter defined for the function. The parameter is in JSON format.
  • Context: runtime information provided for executing the function. For details, see SDK APIs.

Python Initializer

FunctionGraph supports the following Python runtimes:

  • Python 2.7 (runtime = python2.7)
  • Python 3.6 (runtime = python3)
  • Python 3.9 (runtime = python3)
  • Python 3.10 (runtime = python3)

Initializer syntax:

[File name].[Initializer name]

For example, if the initializer is named main.my_initializer, FunctionGraph loads the my_initializer function defined in the main.py file.

To use Python to build initialization logic, define a Python function as the initializer. The following is a simple initializer (Python 2.7 is used as an example):

def my_initializer(context):
    print 'hello world!'
  • Function Name

    The function name my_initializer must be the initializer function name specified for a function. For example, if the initializer is named main.my_initializer, FunctionGraph loads the my_initializer function defined in the main.py file.

  • context

    The context parameter contains the runtime information about a function. For example, request ID, temporary AK, and function metadata.

SDK APIs

Table 1 describes the context methods provided by FunctionGraph.

Table 1 Context methods

Method

Description

getRequestID()

Obtains a request ID.

getRemainingTimeInMilliSeconds ()

Obtains the remaining running time of a function.

getAccessKey()

Obtains the AK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getAccessKey API in the Runtime SDK. You cannot use this API to obtain a temporary AK.

getSecretKey()

Obtains the SK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getSecretKey API in the Runtime SDK. You cannot use this API to obtain a temporary SK.

getSecurityAccessKey()

Obtains the SecurityAccessKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecuritySecretKey()

Obtains the SecuritySecretKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecurityToken()

Obtains the SecurityToken (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getUserData(string key)

Uses keys to obtain the values passed by environment variables.

getFunctionName()

Obtains the name of a function.

getRunningTimeInSeconds ()

Obtains the timeout of a function.

getVersion()

Obtains the version of a function.

getMemorySize()

Obtains the allocated memory.

getCPUNumber()

CPU usage of a function.

getPackage()

Obtains a function group, that is, an app.

getToken()

Obtains the token (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getLogger()

Obtains the logger method provided by the context and returns a log output class. Logs are output in the format of Time-Request ID-Content by using the info method.

For example, use the info method to output logs:

log = context.getLogger()

log.info("test")

getAlias

Obtains function alias.

NOTICE:

Results returned by using the getToken(), getAccessKey(), and getSecretKey() methods contain sensitive information. Exercise caution when using these methods.

Developing a Python Function

Perform the following steps to develop a Python function:

NOTE:

Python 2.7 is used an example.

  1. Create a function project.

    1. Write code for printing text helloworld.

      Open the text editor, compile a HelloWorld function, and save the code file as helloworld.py. The code is as follows:

      1
      2
      def printhello():
          print 'hello world!'
      
    2. Define a FunctionGraph function.

      Open the text editor, define a function, and save the function file as index.py under the same directory as the helloworld.py file. The function code is as follows:

      1
      2
      3
      4
      5
      6
      7
      import json
      import helloworld
      
      def handler (event, context):
          output =json.dumps(event)
          helloworld.printhello()
          return output
      
    NOTE:

    FunctionGraph can return only the following types of values:

    • None: The HTTP response body is empty.
    • String: The content in this string is the body of an HTTP response.
    • Other: For a value rather than None or String, FunctionGraph encodes the value in JSON, and uses the encoded object as the body of an HTTP response. The Content-Type header of the HTTP response is set to application/json.
    • For details about the constraints for the APIG event source, see Base64 Decoding and Response Structure.

  2. Package the project files.

    After creating the function project, you get the following directory. Select all files under the directory and package them into the fss_examples_python2.7.zip file, as shown in Figure 1.

    Figure 1 Packaging the project files
    NOTICE:
    • In this example, the function project files are saved under the ~/code/ directory. Select and package all files under the directory to ensure that the index.py file, the handler of your FunctionGraph function, is under the root directory when the fss_examples_python2.7.zip file is decompressed.
    • When you write code in Python, do not name your package with the same suffix as a standard Python library, such as json, lib, and os. Otherwise, an error will be reported indicating a module loading failure.

  3. Create a FunctionGraph function and upload the code package.

    Log in to the FunctionGraph console, create a Python function, and upload the fss_examples_python2.7.zip file, as shown in Figure 2.

    Figure 2 Uploading the code package

    NOTE:
    1. The index of the handler must be consistent with the name of the file created in Step 1 (2), because the file name will help to locate the function file.
    2. The handler is the function name, which must be the same as that in the index.py file created in Step 1 (2).
    3. After you upload the fss_examples_python2.7.zip file to OBS, when the function is triggered, FunctionGraph decompresses the file to locate the function file through index and locate the function defined in the index.py file through handler, and then executes the function.

    In the navigation pane on the left of the FunctionGraph console, choose Functions > Function List. Click the name of the function to be set. On the function details page that is displayed, choose Configuration > Basic Settings and set the Handler parameter, as shown in Figure 3. The parameter value is in the format of index.handler. The values of index and handler can be customized.

    Figure 3 Handler parameter

  4. Test the function.

    1. Create a test event.

      On the function details page that is displayed, click Configure Test Event. Configure the test event information, as shown in Figure 4, and then click Create.

      Figure 4 Configuring a test event
    2. On the function details page, select the configured test event, and click Test.

  5. View the function execution result.

    The function execution result consists of three parts: function output (returned by callback), summary, and logs (output by using the print() method), as shown in Figure 5.

    Figure 5 Test result

Execution Result

The execution result consists of the function output, summary, and log output.

Table 2 Description of the execution result

Parameter

Successful Execution

Failed Execution

Function Output

The defined function output information is returned.

A JSON file that contains errorMessage, errorType, and stackTrace is returned. The format is as follows:

{
    "errorMessage": "",
    "errorType": "",
    "stackTrace": []
}

errorMessage: Error message returned by the runtime.

errorType: Error type.

stackTrace: Stack error information returned by the runtime.

Summary

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Log Output

Function logs are printed. A maximum of 4 KB logs can be displayed.

Error information is printed. A maximum of 4 KB logs can be displayed.

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback