如何使用AWS Lambda将文件写入s3(python)? [英] How could I use aws lambda to write file to s3 (python)?

查看:589
本文介绍了如何使用AWS Lambda将文件写入s3(python)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用lambda函数将文件写入S3,然后测试显示成功",但是S3存储桶中没有任何显示.发生了什么?有人可以给我一些建议或解决方案吗?非常感谢.这是我的代码.

I have tried to use lambda function to write a file to S3, then test shows "succeeded" ,but nothing appeared in my S3 bucket. What happened? Does anyone can give me some advice or solutions? Thanks a lot. Here's my code.

import json
import boto3

def lambda_handler(event, context):

string = "dfghj"

file_name = "hello.txt"
lambda_path = "/tmp/" + file_name
s3_path = "/100001/20180223/" + file_name

with open(lambda_path, 'w+') as file:
    file.write(string)
    file.close()

s3 = boto3.resource('s3')
s3.meta.client.upload_file(lambda_path, 's3bucket', s3_path)

推荐答案

我已经成功将数据流传输到S3,必须对此进行编码:

I've had success streaming data to S3, it has to be encoded to do this:

import boto3

def lambda_handler(event, context):
    string = "dfghj"
    encoded_string = string.encode("utf-8")

    bucket_name = "s3bucket"
    file_name = "hello.txt"
    lambda_path = "/tmp/" + file_name
    s3_path = "/100001/20180223/" + file_name

    s3 = boto3.resource("s3")
    s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string)

如果数据在文件中,则可以读取此文件并将其发送:

If the data is in a file, you can read this file and send it up:

with open(filename) as f:
    string = f.read()

encoded_string = string.encode("utf-8")

这篇关于如何使用AWS Lambda将文件写入s3(python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆