利用函数计算对oss压缩文件做自动解压处理

本文涉及的产品
简介: 函数计算提供了一种事件驱动的计算模型。函数的执行是由事件驱动的,函数计算触发器描述了一组规则,当某个事件满足这些规则,事件源就会触发相应的函数。

前言

一个应用可能已经使用对象存储(Object Storage Service,简称OSS)来存放用户上传的图片,用户可以实现一个函数去下载图片进行处理,并将结果存入OSS或者其他服务。如果OSS能够帮助我们关注新上传的图片,并且自动的去调用执行相应的处理函数,用户就不需要再去自己调用函数了,从而简化了开发和使用流程。
函数计算提供了一种事件驱动的计算模型。函数的执行是由事件驱动的,函数计算触发器描述了一组规则,当某个事件满足这些规则,事件源就会触发相应的函数。

repo 工程: fc-decompress-oss

示例内容

在本教程示例中,一个被存入OSS的文件,如果它是以source/为前缀,并且后缀是.gz .tar .zip的文件,那么OSS就会自动的调用相应的函数进行解压处理。

# -*- coding: utf-8 -*-
import oss2, json
import gzip
import tarfile 
import zipfile
import os
import cStringIO


# This template code can decompress the following three types of compression files.
#.gz .tar  .zip 
# if you want uncompress rar or for more info
# please refer to https://yq.aliyun.com/articles/468050?spm=a2c4e.11153959.teamhomeleft.1.1534d3c20HYMx5

def handler(event, context):
    """
    The object from OSS will be decompressed automatically .
    param: event:   The OSS event json string. Including oss object uri and other information.
    
    param: context: The function context, including credential and runtime info.

            For detail info, please refer to https://help.aliyun.com/document_detail/56316.html#using-context
    """
    evt_lst = json.loads(event)
    creds = context.credentials
    # Required by OSS sdk
    auth=oss2.StsAuth(
        creds.access_key_id,
        creds.access_key_secret,
        creds.security_token)
    evt = evt_lst['events'][0]
    bucket_name = evt['oss']['bucket']['name']
    endpoint = 'oss-' +  evt['region'] + '.aliyuncs.com'
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    object_name = evt['oss']['object']['key']

    """
    When a source/ prefix object is placed in an OSS, it is hoped that the object will be decompressed and then stored in the OSS as processed/ prefixed.
    For example, source/a.zip will be processed as processed/a/... 
    "Source /", "processed/" can be changed according to the user's requirements.
    """

    newKey = object_name.replace("source/", "processed/")
    remote_stream = bucket.get_object(object_name)
    if not remote_stream:
        raise RuntimeError('failed to get oss object. bucket: %s. object: %s' % (bucket_name, object_name))

    print 'download object from oss success: {}'.format(object_name)

    file_type = os.path.splitext(object_name)[1]


    if file_type == ".gz":
        data = cStringIO.StringIO(remote_stream.read())
        newKey = newKey.strip()[:-3]
        with gzip.GzipFile(mode = 'rb', fileobj = data) as f:
            r_data = f.read()  
            bucket.put_object(newKey, r_data)
            
    elif file_type == ".tar":
        data = cStringIO.StringIO(remote_stream.read())
        with tarfile.TarFile(mode = 'r', fileobj = data) as tar:
            newKey.replace(".tar", "")
            names = tar.getnames()
            for name in names:
                r = tar.extractfile(name)
                if r: # filter folder
                    bucket.put_object(newKey +  name, r.read())
                    r.close()
                    
    elif file_type == ".zip":
        data = cStringIO.StringIO(remote_stream.read())
        with zipfile.ZipFile(data,"r") as zip_file:
            newKey.replace(".zip", "")
            for name in zip_file.namelist():
                file = zip_file.open(name)
                r_data = file.read()
                if r_data: # filter folder
                    bucket.put_object(newKey +  name, r_data)
                file.close()

FAQ

如果是文件是后缀是.rar ,怎么解?

rar 这种格式如果用python,需要依赖第三方module和二进制文件,附件提供代码下载

相关实践学习
基于函数计算一键部署掌上游戏机
本场景介绍如何使用阿里云计算服务命令快速搭建一个掌上游戏机。
建立 Serverless 思维
本课程包括: Serverless 应用引擎的概念, 为开发者带来的实际价值, 以及让您了解常见的 Serverless 架构模式
目录
相关文章
|
26天前
|
监控 Serverless 测试技术
Serverless 应用引擎常见问题之生成的图片的oss地址配成自定义的域名如何解决
Serverless 应用引擎(Serverless Application Engine, SAE)是一种完全托管的应用平台,它允许开发者无需管理服务器即可构建和部署应用。以下是Serverless 应用引擎使用过程中的一些常见问题及其答案的汇总:
22 0
|
17天前
|
存储 Cloud Native Serverless
云原生最佳实践系列 7:基于 OSS Object FC 实现非结构化文件实时处理
阿里云OSS对象存储方案利用函数计算FC,在不同终端请求时实时处理OSS中的原图,减少衍生图存储,降低成本。
|
3月前
|
JavaScript Java Serverless
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
函数计算中,这里是用的curl的方式,如何改用http的post方式请求?还有如何设置oss打包的zip的保存目录?
159 0
|
4月前
|
Serverless 对象存储 数据安全/隐私保护
在阿里云函数计算(FC)中使用云对象存储服务(OSS)时,需要为FC实例授予对OSS资源的访问权限
在阿里云函数计算(FC)中使用云对象存储服务(OSS)时,需要为FC实例授予对OSS资源的访问权限
370 1
|
7月前
|
存储 弹性计算 Serverless
使用函数计算打包下载OSS文件
本场景介绍如何使用函数计算将对象存储OSS上多个文件(Object)打包下载到本地。
424 0
|
存储 Serverless 对象存储
函数计算批量处理海量 OSS 文件
函数计算批量处理海量 OSS 文件自制脑图
96 0
函数计算批量处理海量 OSS 文件
|
存储 人工智能 JSON
函数计算与对象存储实现WordCount
Serverless架构可以在很多领域发挥极具价值的作用。包括监控告警、人工智能、图像处理、音视频处理等,同样,在大数据领域,Serverless架构仍然可以具有良好的表现,以大数据常见的入门案例:WordCount为例,可以依靠Serverless架构实现一个“Serverless版本的MapReduce”。
102 0
|
监控 关系型数据库 Serverless
基于 Serverless+OSS 分分钟实现图片秒变素描
在阿里云 Serverless 函数计算服务中部署普通图片转素描图的函数服务,实现批量上传到指定 OSS 桶内的图片自动转换为素描图并保存到另一个 OSS 桶内。
基于 Serverless+OSS 分分钟实现图片秒变素描
|
监控 关系型数据库 Serverless
|
监控 关系型数据库 Serverless
基于Serverless+OSS分分钟实现图片秒变素描
在阿里云Serverless函数计算服务中部署普通图片转素描图函数服务,实现将批量上传到指定OSS桶内的图片自动转换为素描图并保存到另一个OSS桶内
基于Serverless+OSS分分钟实现图片秒变素描

相关产品

  • 函数计算