如何在不保存文件的情况下将 Python 请求内容上传到 S3

How to upload a Python Requests content to S3 without saving the file

我是 运行 Python Lambda 函数,它使用 Requests 库从服务器下载 MP3 文件,然后将文件上传到 S3。这是我正在使用的代码,运行良好:

dl_url = "https://server.com/file.mp3"
response = requests.get(dl_url)
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
file_name = "file.mp3"
dir_file = f"/tmp/{file_name}"

with open(dir_file, "wb") as f:
    f.write(response.content)

bucket.upload_file(dir_file, file_name)

这段代码工作正常,但是我想知道我是否可以跳过先保存文件然后上传文件的步骤。

不需要您先保存文件的工作代码:

import boto3
import requests

s3_client = boto3.client('s3')

bucket = "test-bucket"

dl_url = "https://file-examples.com/storage/fe1170c1cf625dc95987de5/2017/11/file_example_MP3_700KB.mp3"
response = requests.get(dl_url)

# Write the object
s3_client.put_object(Bucket=bucket,
                     Key="sample_mp3.mp3",
                     Body=response.content)