python - 我如何使用 aws lambda 将文件写入 s3 (python)?

标签 python amazon-web-services amazon-s3 aws-lambda serverless-framework

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

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,必须对其进行编码才能执行此操作:

import boto3

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

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

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

如果数据在一个文件中,你可以读取这个文件并发送:

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

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

关于python - 我如何使用 aws lambda 将文件写入 s3 (python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945389/

相关文章:

python - 将 Keras 模型应用于符号张量的 TF2.0 内存泄漏

python - boto3.Bucket.upload_file 是阻塞还是非阻塞?

python - 没有获得与分配标签相关的特定成本

python - 我怎样才能摆脱 yield 并在我的代码中使用另一个函数

python - 定义在 Python 中给出给定范围内的随机值的函数

python - 当我输入 python 时,CMD 打开窗口存储

amazon-web-services - 无法使用 session 管理器连接 EC2 实例

amazon-web-services - 在 Amazon S3 预签名 URL 上传后获取 AWS lambda 响应

object - 如何从 s3 url 获取文件(前 n 个字节)

amazon-web-services - AWS CloudFront 和 S3 : How to make new S3 content immediately available in CloudFront?