![](/img/trans.png)
[英]Write csv file and save it into S3 using AWS Lambda (python)
[英]How could I use aws lambda to write file to s3 (python)?
我嘗試使用 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")
我的回答與 Tim B 非常相似,但最重要的部分是
1.轉到S3存儲桶並創建一個要寫入的存儲桶
2.按照以下步驟操作,否則您的 lambda 將因權限/訪問而失敗。 我也為您復制並粘貼了此處的鏈接內容,以防萬一他們更改網址/將其移動到其他頁面。
一個。 在 IAM 控制台中打開角色頁面。
灣。 選擇創建角色。
C。 創建具有以下屬性的角色。
- 受信任的實體——AWS Lambda。
- 權限 – AWSLambdaExecute。
-角色名稱 - lambda-s3-role。
AWSLambdaExecute 策略具有該函數管理 Amazon S3 中的對象並將日志寫入 CloudWatch Logs 所需的權限。
將其復制並粘貼到您的 Lambda python 函數中
import json, boto3,os, sys, uuid from urllib.parse import unquote_plus s3_client = boto3.client('s3') def lambda_handler(event, context): some_text = "test" #put the bucket name you create in step 1 bucket_name = "my_buck_name" file_name = "my_test_file.csv" lambda_path = "/tmp/" + file_name s3_path = "output/" + file_name os.system('echo testing... >'+lambda_path) s3 = boto3.resource("s3") s3.meta.client.upload_file(lambda_path, bucket_name, file_name) return { 'statusCode': 200, 'body': json.dumps('file is created in:'+s3_path) }
from os import path
import json, boto3, sys, uuid
import requests
s3_client = boto3.client('s3')
def lambda_handler(event, context):
bucket_name = "mybucket"
url = "https://i.imgur.com/ExdKOOz.png"
reqponse = requests.get(url)
filenname = get_filename(url)
img = reqponse.content
s3 = boto3.resource("s3")
s3.Bucket(bucket_name).put_object(Key=filenname, Body=img)
return {'statusCode': 200,'body': json.dumps('file is created in:')}
def get_filename(url):
fragment_removed = url.split("#")[0]
query_string_removed = fragment_removed.split("?")[0]
scheme_removed = query_string_removed.split("://")[-1].split(":")[-1]
if scheme_removed.find("/") == -1:
return ""
return path.basename(scheme_removed)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.