首页 文章

从OpenWhisk(IBM Cloud Function)操作返回二进制HTTP响应

提问于
浏览
1

我想在IBM Cloud Function中使用OpenWhisk通过HTTP返回驻留在(IBM Cloud)ObjectStorage中的二进制文件 .

这可能吗?对我而言,似乎OpenWhisk仅支持JSON作为动作的结果 .

这是我正在使用的代码(get_object_storage_file返回二进制数据):

import sys
from io import StringIO
import requests
import json

def get_object_storage_file(container, filename):
    """This functions returns a StringIO object containing
    the file content from Bluemix Object Storage."""

    url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
    data = {'auth': {'identity': {'methods': ['password'],
            'password': {'user': {'name': 'member_1feaf9dc308e9d57b5fce8a2424e51cd3f04af17','domain': {'id': '4619da2fa8524beda11c89d2d1969c5b'},
            'password': 'nviJ.XXXXXXX.aexT'}}}}}
    headers1 = {'Content-Type': 'application/json'}
    resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
    resp1_body = resp1.json()
    for e1 in resp1_body['token']['catalog']:
        if(e1['type']=='object-store'):
            for e2 in e1['endpoints']:
                        if(e2['interface']=='public'and e2['region']=='dallas'):
                            url2 = ''.join([e2['url'],'/', container, '/', filename])
    s_subject_token = resp1.headers['x-subject-token']
    headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
    resp2 = requests.get(url=url2, headers=headers2)
    return StringIO(resp2.text)

def main(dict):
    get_object_storage_file('data', 'raw.bin')
    return {'greeting':'test'}

1 回答

  • 2

    这是关于网络行动还是“正常”行动?

    通常,您始终可以返回以JSON对象编码的二进制数据的Base64编码表示 . 确实,CloudFunctions操作 always 需要返回一个JSON对象 .

    在您的具体示例中,以下可能有效:

    import base64
    
    def main(dict):
        binary = get_object_storage_file('data', 'raw.bin')
        return {'data':base64.base64encode(binary)}
    

    (未经测试的伪代码)

相关问题