函数工作流 FUNCTIONGRAPH-构建程序:创建程序包

时间:2024-08-12 19:49:34

创建程序包

本例使用Python语言实现图片压缩的功能,有关函数开发的过程请参考Python函数开发。本例不再介绍业务功能实现的代码,样例代码目录如图1所示。

图1 样例代码目录
其中index.py为函数执行的入口文件,index.py中入口函数的代码片段如下,参数“output_bucket”为压缩后的图片存储地址,需要在创建函数时配置自定义参数。
# -*-coding:utf-8 -*-
import os
import string
import random
import urllib.parse
from PIL import Image
from obs import ObsClient

LOCAL_MOUNT_PATH = '/tmp/'


def handler(event, context):
    ak = context.getSecurityAccessKey()
    sk = context.getSecuritySecretKey()
    st = context.getSecurityToken()
    if ak == "" or sk == "" or st == "":
        context.getLogger().error('Failed to access OBS because no temporary '
                                  'AK, SK, or token has been obtained. Please '
                                  'set an agency.')
        return 'Failed to access OBS because no temporary AK, SK, or token ' \
               'has been obtained. Please set an agency. '

    obs_endpoint = context.getUserData('obs_endpoint')
    if not obs_endpoint:
        return 'obs_endpoint is not configured'

    output_bucket = context.getUserData('output_bucket')
    if not output_bucket:
        return 'output_bucket is not configured'

    compress_handler = ThumbnailHandler(context)
    records = event.get("Records", None)
    return compress_handler.run(records[0])
support.huaweicloud.com/bestpractice-functiongraph/functiongraph_05_0302.html