如何将以下直方图上传到存储桶而不保存在磁盘上,然后在Cloud Function中使用?

时间:2019-05-24 15:45:08

标签: python-3.x google-cloud-functions google-cloud-storage

您好,因为我正在设计一个Python云函数来从存储在存储桶中的csv中绘制直方图,

我尝试如下:

def plot(event, context):
    client = storage.Client()
    csv = client.bucket(event['bucket']).blob(event['name']).download_as_string()
    df = pd.read_csv(io.BytesIO(csv), index_col=0)
    objects = df['filepart']
    y_pos = np.arange(len(objects))
    performance = df['confidence']
    plt.bar(y_pos, performance, align='center', alpha=0.99,color='blue')
    plt.xticks(y_pos, objects,rotation=90)
    plt.ylabel('')
    plt.title('')

在这里我将图像保存在磁盘上:

    plt.savefig('foo.png')
    my_bucket = "clusters_sklearn"

然后我将文件名中的文件从以下文件上传到存储桶:

    client = get_client()
    bucket = client.get_bucket(my_bucket)
    bucket.blob("foo.png").upload_from_filename("foo.png")
    with open("foo.png", "rb") as my_file:
        bucket.blob("foo.png").upload_from_file(my_file)

但是,要在云功能中使用此功能,由于我无权访问物理磁盘,因此需要修改此部分:

    plt.savefig('foo.png')

还要修改我从磁盘上传到存储桶的方式:

    bucket.blob("foo.png").upload_from_filename("foo.png")
    with open("foo.png", "rb") as my_file:
        bucket.blob("foo.png").upload_from_file(my_file)

因此,我想感谢支持修改我的代码以便在Google云功能中使用

我的完整代码如下,谢谢:

def plot(event, context):
    client = storage.Client()
    csv = client.bucket(event['bucket']).blob(event['name']).download_as_string()
    df = pd.read_csv(io.BytesIO(csv), index_col=0)
    objects = df['filepart']
    y_pos = np.arange(len(objects))
    performance = df['confidence']
    plt.bar(y_pos, performance, align='center', alpha=0.99,color='blue')
    plt.xticks(y_pos, objects,rotation=90)
    plt.ylabel('')
    plt.title('')
    plt.savefig('foo.png')
    my_bucket = "clusters_sklearn"
    client = get_client()
    bucket = client.get_bucket(my_bucket)
    bucket.blob("foo.png").upload_from_filename("foo.png")
    with open("foo.png", "rb") as my_file:
        bucket.blob("foo.png").upload_from_file(my_file)

0 个答案:

没有答案