簡體   English   中英

如何在不保存文件的情況下將 Python 請求內容上傳到 S3

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

我正在運行 Python Lambda Function 從服務器使用 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM