python - 使用 Lambda 更新文本文件
问题描述
每当我将图像上传到 s3 存储桶时,我都希望能够更新文本文件。此文本文件的每一行都将包含 Amazon Rekognition 的结果。但是,我编写的代码无法正常工作
bucket_name = "update-my-text-file"
rekognition = boto3.client('rekognition')
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
def handle_image(key):
response = rekognition.detect_labels(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': key
}
}
)
return response
def lambda_handler(event, context):
file_name = 'results.txt'
object = s3.Object(bucket_name, 'tmp/results.txt')
cli = boto3.client('s3')
response = cli.get_object(Bucket=bucket_name, Key='tmp/results.txt')
data = response['Body'].read()
print('the data is ' + data)
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
response = handle_image(key)
print('the response is: ' + response)
object.put(Body=data + '/n' + response)
解决方案
您可能会发现像这样下载文件更容易:
import boto3
s3_client = boto3.client('s3')
s3_client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
然后您可以根据需要读/写本地文件。然后,再次上传:
s3_client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
推荐阅读
- php - Ckeditor textarea 的值在第一次提交时未发布,但它适用于第二次提交,其他字段(如图像属性等)是不可编辑的
- reactjs - 使用 React 和 Firestore 数据库的无限循环图像 - 如何获取我的数据?
- next.js - Next JS nextjs 重写未按预期工作
- filepond - 对 Filepond 实例进行编辑后,如何绕过跳过还原和上传?
- ios - 一个模型如何通知另一个模型特定属性发生了变化?
- py2app - 在 py2app 中隐藏默认脚本
- python - pandas 比应用 lambda 在每一行中应用逻辑更快的方法?
- java - 如何修复“编译器为空,也许您在 JRE 环境中,请更改为 JDK 环境”
- python-3.x - 如何在后台运行机器学习训练?
- gitlab - GITLAB CI:文件外壳无法获取环境变量