1.5.2 集成小米FDS服务
优质
小牛编辑
129浏览
2023-12-01
当您在小米FDS上创建或删除了某个对象时,函数计算能够根据您创建的FDSTrigger自动检测到发生的事件,同时触发相关函数的执行。
目前函数计算同时支持新版及旧版FDS,在运行环境Python2及Python3中均可以使用。
如果您想要为上传到FDS中指定bucket的图像创建一个缩略图,可以参考如下代码:
from fds import GalaxyFDSClient,GalaxyFDSClientException,FDSClientConfiguration
import os,sys
from PIL import Image
before_file = DOWNLOAD_IMAGE_FROM_FDS
after_file = UPLOAD_THUMBNAIL_TO_FDS
class FDSConfig:
def __init__(self, AK, SK, ENDPOINT):
self.AK = AK
self.SK = SK
self.ENDPOINT = ENDPOINT
def get_client():
fds_config = _get_FDSConfig()
config = FDSClientConfiguration()
if fds_config.ENDPOINT == None:
print "endpoint is None, please check env $XIAOMI_FDS_ENDPOINT"
return
config.set_endpoint(fds_config.ENDPOINT)
return GalaxyFDSClient(fds_config.AK, fds_config.SK,config)
def _get_FDSConfig():
AK = os.environ.get("AK")
SK = os.environ.get("SK")
ENDPOINT = os.environ.get("XIAOMI_FDS_ENDPOINT")
return FDSConfig(AK, SK, ENDPOINT)
def get_image_from_fds(client,bucket):
file = open(before_file, "w+")
try:
image_object = client.get_object(bucket,object)
for chunk in image_object.stream:
file.write(chunk)
except GalaxyFDSClientException as e:
print e.message
finally:
file.close()
def save_thumbnail():
im = Image.open(before_file)
size = (70,15)
im.thumbnail(size)
im.save(after_file,"png")
im.close()
def put_image_to_fds(client,bucket):
object_name = after_file.split("/")[-1]
image = open(after_file)
client.put_object(bucket,object_name,image)
return object_name
def main(event):
bucket = event['bucketName']
object = event['objectName']
print "start function"
client = get_client()
if not client.does_bucket_exist(bucket) :
print "bucket [%s] not exist ,please create first" %bucket
return False
get_image_from_fds(client,bucket)
save_thumbnail()
after_object_name = put_image_to_fds(client,bucket)
if client.does_object_exists(bucket, after_object_name):
print "thunmbnail has uploaded to FDS , object is [%s]" %after_object_name
return True
return False
在您使用这个函数时,请参考下图设置环境变量AK,SK及XIAOMI_FDS_ENDPOINT,示例代码是通过这三个环境变量,调用FDS的sdk,完成获取及上传图片的功能,同时请修改代码中“before_file”,“after_file”这两个变量。
请注意AK/SK两个参数,如果您使用老版FDS,需要由dev.mi.com的密钥中心获取AK/SK,如果您使用新版FDS,请从用户管理中获取AK/SK event参数为dict类型,内容如下,请根据您的需求进行编码,其中action字段有两种取值:“PutObject”,“DeleteObject”:
{
"bucketName":"test-fds",
"objectName":"image.png",
"action":"ACTION",
"uuid":"3535a4ce-010b-42f2-bce9-ffb46d421aa5",
"timestamp":1506305123069,
"versionId":"12345"
}