将wordcloud绘图从AWS lambda保存到S3 bucket



我目前正试图将我在AWS lambda函数中生成的单词cloud保存到我的s3 bucket中,我的代码执行gut-gives"errorMessage":"参数验证失败:\n参数Body的类型无效,值:<wordcloud.wordcloud.wordcloud对象位于0x7f36643fce10>,类型:<类"wordcloud.wordcloud.wordcloud">,有效类型:<类"字节">lt;类"字节数组">,文件状对象";,

作为一个错误,我在网上查看了一下,似乎找不到原因,我需要将绘图转换为字节才能像这样存储在S3中吗?

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import boto3
text = "cat cat cat dog dog dog test test hello one two three four five"
generate_word_cloud(text)

def generate_word_cloud(text):
wordcloud = WordCloud(width = 3000, 
height = 2000, 
random_state=1, 
background_color='salmon', 
colormap='Pastel1', 
collocations=False, 
stopwords = STOPWORDS).generate(text)
save_to_bucket(wordcloud)

def save_to_bucket(wordcloud):
#Save tweet list to an s3 bucket
BUCKET_NAME = "1706224-tweets"
FILE_NAME = "wordcloud.png"
s3 = boto3.resource('s3')
object = s3.Object(BUCKET_NAME, FILE_NAME)
object.put(Body=wordcloud)

最后,我使用lambda中的/tmp存储来临时存储图像,然后在后上传图像

wordcloud.to_file("/tmp/"+FILE_NAME)
s3 = boto3.client('s3')
s3.upload_file("/tmp/"+FILE_NAME,BUCKET_NAME,FILE_NAME)

您可以将PIL映像转换为字节数组并使用它,例如,在您的情况下,您可以在save_to_bucket方法中执行以下操作


def save_to_bucket(wordcloud):
#Save tweet list to an s3 bucket
BUCKET_NAME = "1706224-tweets"
FILE_NAME = "wordcloud.png"
s3 = boto3.resource('s3')
object = s3.Object(BUCKET_NAME, FILE_NAME)
// here you convert the PIL image that generate wordcloud to byte array
image_byte = image_to_byte_array(wordcloud.to_image())
object.put(Body=image_byte)

def image_to_byte_array(image: Image, format: str = 'png'):
result = io.BytesIO()
image.save(result, format=format)
result = result.getvalue()
return result

最新更新