本文介绍了python - 使用 matplotlib 和 boto 从内存上传绘图到 s3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的工作脚本,用于生成绘图、将其本地保存到磁盘、上传到 S3 并删除文件:
This is my working script that generates a plot, saves it locally to disk, uploads to S3 and deletes the file:
plt.figure(figsize=(6,6))
plt.plot(x, y, 'bo')
plt.savefig('file_location')
conn = boto.s3.connect_to_region(
region_name=AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
calling_format=boto.s3.connection.OrdinaryCallingFormat()
)
bucket = conn.get_bucket('bucket_name')
k = Key(bucket)
k.key = 'file_name'
k.set_contents_from_filename('file_location')
os.remove(file_location)
我想要的是跳过磁盘写入并直接从内存上传情节.
What I want is to skip the disk writing and upload the plot directly from memory.
对于如何实现这一目标有什么建议吗?
Any suggestions how to achieve that?
推荐答案
综合起来:
img_data = io.BytesIO()
plt.savefig(img_data, format='png')
img_data.seek(0)
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
bucket.put_object(Body=img_data, ContentType='image/png', Key=KEY)
感谢@padraic-cunningham 和@guyb7 的提示!
Thanks @padraic-cunningham and @guyb7 for the tips!
这篇关于python - 使用 matplotlib 和 boto 从内存上传绘图到 s3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!