开发者社区 > 云原生 > Serverless > 正文

请教个问题,有大佬知道 使用函数计算打包下载OSS文件 用sdk调用,参数应该怎么传吗?官方文档上细

请教个问题,有大佬知道 使用函数计算打包下载OSS文件 用sdk调用,参数应该怎么传吗?官方文档上细节都没有 https://help.aliyun.com/document_detail/158322.html

提问34.png

展开
收起
飘飘斯嘉丽 2023-02-10 11:54:22 722 0
2 条回答
写回答
取消 提交回答
  • 就是直接请求触发器url 传这个参数就可以了

    回答8.png

    此答案来自钉钉群“阿里函数计算官网客户"

    2023-02-10 18:12:21
    赞同 展开评论 打赏
  • 发表文章、提出问题、分享经验、结交志同道合的朋友

    建议在函数计算里新建一个python文件调用oss相关功能 相关python代码参考:

    # -*- coding: utf-8 -*-
    
    import logging
    import oss2
    import zipfile
    import json
    import base64
    import os
    import time
    from urllib.parse import urlparse
    from urllib.parse import parse_qs
    
    LOGGER = logging.getLogger()
    ossClient = None
    
    def initializer(context):
       # 初始化OSS Client
       ak = context.credentials.accessKeyId
       sk = context.credentials.accessKeySecret
       securityToken = context.credentials.securityToken
       global ossClient
       ossClient = oss2.StsAuth(ak, sk, securityToken)
    
    # 计算文件名和扩展名
    def getFileNameExt(filename):
        (fileDir, tempfilename) = os.path.split(filename)
        (shortname, extension) = os.path.splitext(tempfilename)
        return shortname, extension
    
    # 压缩指定目录下的文件
    def zipDir(filePath, outFullName):
        zip = zipfile.ZipFile(outFullName, mode="w")
        for path, dirnames, filenames in os.walk(filePath):
            fpath = path.replace(filePath, '')
            for filename in filenames:
                zip.write(os.path.join(path, filename))
        zip.close()
    
    def handler(environ, start_response):
        context = environ['fc.context']
        request_uri = environ['fc.request_uri']
        for k, v in environ.items():
          if k.startswith('HTTP_'):
            # process custom request headers
            pass
      
        # 处理URL
        urlObj = urlparse(request_uri)
        urlQuery = parse_qs(urlObj.query)
    
    
        # 待压缩文件的OSS Bucket
        var sourceBucket = process.env['sourceBucket']
        # 待压缩文件的OSS Endpoint
        var sourceEndpoint = process.env['sourceEndpoint']
        #sourceBucket = urlQuery['sourceBucket'][0]
        #sourceEndpoint = urlQuery['sourceEndpoint'][0]
    
        # 待压缩文件的OSS路径
        sourceResourcePaths = urlQuery['sourceResourcePaths'][0]
        sourceResourcePathsArray = sourceResourcePaths.split(',')
    
        # 待压缩资源列表文件的路径
        sourceResourceFilePath = str(base64.urlsafe_b64decode(urlQuery['sourceResourceFilePath'][0]), 'utf-8')
        # 待压缩资源列表文件的名称
        sourceResourceFileName = urlQuery['sourceResourceFileName'][0]
    
        # 目标压缩包文件名称
        saveAsFileName = urlQuery['saveAsFileName'][0]
        # 目标压缩包上传路径
        var saveAsPath = process.env['saveAsPath']
        #saveAsPath = str(base64.urlsafe_b64decode(urlQuery['saveAsPath'][0]), 'utf-8')
        saveAsPathAndFileName = saveAsPath + saveAsFileName
    
        # 目标压缩包上传Bucket
        var saveAsBucket = process.env['saveAsBucket']
        #saveAsBucket = urlQuery['saveAsBucket'][0]
        # 目标压缩包上传Endpoint
        var saveAsEndpoint = process.env['saveAsEndpoint']
        #saveAsEndpoint = urlQuery['saveAsEndpoint'][0]
    
        # 初始化待压缩文件的Bucket Client
        global ossClient
        sourceBucketObj = oss2.Bucket(ossClient, sourceEndpoint, sourceBucket) 
    
        # 暂时使用内存存储
        t = time.time()
        # 存放待压缩文件的路径
        localUnzipPath = '/tmp/unzip' + str(int(t)) + '/'
        os.mkdir(localUnzipPath)
        os.system("chmod -R 777 " + localUnzipPath)
        # 压缩包文件存放路径
        localZipPath = '/tmp/zip' + str(int(t)) + '/'
        os.mkdir(localZipPath)
        os.system("chmod -R 777 " + localZipPath)
        tmpPath = '/tmp/'
    
        zipMode = urlQuery['zipMode'][0]
        # 少量文件压缩模式
        if zipMode == '1':
            for objPath in sourceResourcePathsArray:
                # Base64解码
                objPathDecode = str(base64.urlsafe_b64decode(objPath), 'utf-8')
                shortName, extension = getFileNameExt(objPathDecode)
                # 下载文件
                sourceBucketObj.get_object_to_file(objPathDecode, localUnzipPath + shortName + extension)
            # 压缩文件
            zipDir(localUnzipPath, localZipPath + saveAsFileName)
    
            # 初始化目标Bucket
            saveAsBucketObj = oss2.Bucket(ossClient, saveAsEndpoint, saveAsBucket) 
            # 上传文件
            saveAsBucketObj.put_object_from_file(saveAsPathAndFileName, localZipPath + saveAsFileName)
        elif zipMode == '2': # 大量文件压缩模式
            # 从资源列表文件中下载文件
            sourceBucketObj.get_object_to_file(sourceResourceFilePath + sourceResourceFileName, tmpPath + sourceResourceFileName)
            sourceResourceFileObj = open(tmpPath + sourceResourceFileName, 'r')
            sourceResourcePathsArray = sourceResourceFileObj.read().split(',')
            sourceResourceFileObj.close()
            
            for objPath in sourceResourcePathsArray:
                # Base64解码
                objPathDecode = str(base64.urlsafe_b64decode(objPath), 'utf-8')
                shortName, extension = getFileNameExt(objPathDecode)
                # 下载文件
                sourceBucketObj.get_object_to_file(objPathDecode, localUnzipPath + shortName + extension)
            # 压缩文件
            zipDir(localUnzipPath, localZipPath + saveAsFileName)
    
            # 初始化目标Bucket
            saveAsBucketObj = oss2.Bucket(ossClient, saveAsEndpoint, saveAsBucket) 
            # 上传文件
            saveAsBucketObj.put_object_from_file(saveAsPathAndFileName, localZipPath + saveAsFileName)
    
    
        status = '200 OK'
        response_headers = [('Content-type', 'text/plain')]
        start_response(status, response_headers)
        return [('https://' + saveAsBucket + '.' + saveAsEndpoint + '/' + saveAsPathAndFileName).encode()]
    
    2023-02-10 16:23:11
    赞同 展开评论 打赏

快速交付实现商业价值。

相关产品

  • 函数计算
  • 热门讨论

    热门文章

    相关电子书

    更多
    OSS运维进阶实战手册 立即下载
    《OSS运维基础实战手册》 立即下载
    OSS运维基础实战手册 立即下载