集成小米FDS

当您在小米FDS上创建或删除了某个对象时,函数计算能够根据您创建的FDSTrigger自动检测到发生的事件,同时触发相关函数的执行。

目前函数计算同时支持新版及旧版FDS,在运行环境Python2及Python3中均可以使用。

如果您想要为上传到FDS中指定bucket的图像创建一个缩略图,可以参考如下代码:

  1. from fds import GalaxyFDSClient,GalaxyFDSClientException,FDSClientConfiguration
  2. import os,sys
  3. from PIL import Image
  4. before_file = DOWNLOAD_IMAGE_FROM_FDS
  5. after_file = UPLOAD_THUMBNAIL_TO_FDS
  6. class FDSConfig:
  7. def __init__(self, AK, SK, ENDPOINT):
  8. self.AK = AK
  9. self.SK = SK
  10. self.ENDPOINT = ENDPOINT
  11. def get_client():
  12. fds_config = _get_FDSConfig()
  13. config = FDSClientConfiguration()
  14. if fds_config.ENDPOINT == None:
  15. print "endpoint is None, please check env $XIAOMI_FDS_ENDPOINT"
  16. return
  17. config.set_endpoint(fds_config.ENDPOINT)
  18. return GalaxyFDSClient(fds_config.AK, fds_config.SK,config)
  19. def _get_FDSConfig():
  20. AK = os.environ.get("AK")
  21. SK = os.environ.get("SK")
  22. ENDPOINT = os.environ.get("XIAOMI_FDS_ENDPOINT")
  23. return FDSConfig(AK, SK, ENDPOINT)
  24. def get_image_from_fds(client,bucket):
  25. file = open(before_file, "w+")
  26. try:
  27. image_object = client.get_object(bucket,object)
  28. for chunk in image_object.stream:
  29. file.write(chunk)
  30. except GalaxyFDSClientException as e:
  31. print e.message
  32. finally:
  33. file.close()
  34. def save_thumbnail():
  35. im = Image.open(before_file)
  36. size = (70,15)
  37. im.thumbnail(size)
  38. im.save(after_file,"png")
  39. im.close()
  40. def put_image_to_fds(client,bucket):
  41. object_name = after_file.split("/")[-1]
  42. image = open(after_file)
  43. client.put_object(bucket,object_name,image)
  44. return object_name
  45. def main(event):
  46. bucket = event['bucketName']
  47. object = event['objectName']
  48. print "start function"
  49. client = get_client()
  50. if not client.does_bucket_exist(bucket) :
  51. print "bucket [%s] not exist ,please create first" %bucket
  52. return False
  53. get_image_from_fds(client,bucket)
  54. save_thumbnail()
  55. after_object_name = put_image_to_fds(client,bucket)
  56. if client.does_object_exists(bucket, after_object_name):
  57. print "thunmbnail has uploaded to FDS , object is [%s]" %after_object_name
  58. return True
  59. return False

在您使用这个函数时,请参考下图设置环境变量AK,SK及XIAOMI_FDS_ENDPOINT,示例代码是通过这三个环境变量,调用FDS的sdk,完成获取及上传图片的功能,同时请修改代码中“before_file”,“after_file”这两个变量。

请注意AK/SK两个参数,如果您使用老版FDS,需要由dev.mi.com的密钥中心获取AK/SK,如果您使用新版FDS,请从用户管理中获取AK/SKAlt textevent参数为dict类型,内容如下,请根据您的需求进行编码,其中action字段有两种取值:“PutObject”,“DeleteObject”:

  1. {
  2. "bucketName":"test-fds",
  3. "objectName":"image.png",
  4. "action":"ACTION",
  5. "uuid":"3535a4ce-010b-42f2-bce9-ffb46d421aa5",
  6. "timestamp":1506305123069,
  7. "versionId":"12345"
  8. }

原文: http://docs.api.xiaomi.com/faas/应用示例/section3.html