将文件直接从Heroku的flask应用程序写入S3 Bucket

时间:2018-02-17 00:50:49

标签: python amazon-web-services amazon-s3

我正在开展一个烧瓶项目,我正在从python词典中创建一个JSON文件。我想将我的JSON文件直接推送到s3存储桶。 我怎样才能做到这一点?

示例数据:

    data = {
    'uid': userId,
    'descriptions': description,
    'inputs': inputs,
    'outputs': outputs,
    'ex_inputs': example_input,
    'ex_outputs': example_output,
    'miscs': misc,
    'constraints': constraints
}

json_data = json.dumps(data, indent=4, ensure_ascii=False)

2 个答案:

答案 0 :(得分:1)

您需要使用boto3库与您的python应用程序中的S3对话。

此链接可能是您的良好开端 - http://boto3.readthedocs.io/en/latest/guide/s3-examples.html

import json
import boto3

data = {}
data['name'] = "foo"
data['description'] = "bar"
json_data = json.dumps(data, ensure_ascii=False)

s3 = boto3.client('s3')
s3.put_object(Bucket='my-bucket', Key='key-name', Body=json_data)

put_object() - https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object

答案 1 :(得分:0)

它正在使用S3 put_object方法。 我的更新代码如下:

key = 'description_' + str(fid) + '.json'
response = s3.put_object(Bucket='d2c-api2-bucket',
                         Body=json_data,
                         Key=key
                         )