[Python] How to save a file to a cloud storage bucket from a cloud run function

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am super new to using google cloud and a very novice coder. I am trying to create an automated system that saves a graph as a jpeg in a cloud storage bucket (this will be a cloud run function that is triggered on a cloud schedule job). The files saving will then trigger another cloud run function to fetch the images and format them in html to send out as an email with Klaviyo's API.

    I can get the second function to send the email to work so I have at least some understanding of making a cloud run function. But I cannot get the fist function to save files to the cloud storage. I get a 500 error.

    Error details: I get two errors:

    POST 500 188 B 23 ms Google-Cloud-Scheduler https://generate-and-upload-1017454958754.us-central1.run.app/

    {"@type":"type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished", "debugInfo":"URL_UNREACHABLE-UNREACHABLE_5xx. Original HTTP response code number = 500", "jobName":"projects/data-email-automation/locations/us-central1/jobs/start-generate-and-upload", "status":"INTERNAL", "targetType":"HTTP", "url":"https://generate-and-upload-1017454958754.us-central1.run.app/"}

    I also get the error message I laid out in my code but this is not marked as an error: Error: your-image-bucket-name environment variable not set.

    Here is the code for the first cloud run function (AI helped me here):

    import functions_framework
    from google.cloud import storage
    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    import io
    import os
    from datetime import datetime


    def generate_image_bytes():
    """Generates a random line graph as JPEG bytes."""
    try:
    num_points = 20
    data = {
    'X': np.arange(num_points),
    'Y1': np.random.rand(num_points) * 10,
    'Y2': np.random.rand(num_points) * 15 + 5,
    'Y3': np.random.randn(num_points) * 5,
    }
    df = pd.DataFrame(data)

    plt.figure(figsize=(10, 6))
    plt.plot(df['X'], df['Y1'], label='Data Series 1', marker='o')
    plt.plot(df['X'], df['Y2'], label='Data Series 2', marker='x')
    plt.plot(df['X'], df['Y3'], label='Data Series 3', marker='+')
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis Value")
    plt.title("Automated Line Graph")
    plt.legend()
    plt.grid(True)

    buffer = io.BytesIO()
    plt.savefig(buffer, format='jpeg', dpi=300, bbox_inches='tight')
    buffer.seek(0)
    plt.close()
    return buffer.getvalue()
    except Exception as e:
    print(f"Error generating image: {e}")
    return None

    @functions_framework.http
    def generate_and_upload(request):
    """Generates an image and uploads it to Cloud Storage."""
    bucket_name = os.environ.get("your-image-bucket-name")
    if not bucket_name:
    error_message = "Error: your-image-bucket-name environment variable not set."
    print(error_message)
    return error_message, 500

    image_bytes = generate_image_bytes()
    if image_bytes:
    client = storage.Client()
    bucket = client.bucket(bucket_name)
    filename = f"automated_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpeg"
    blob = bucket.blob(filename)
    try:
    blob.upload_from_string(image_bytes, content_type="image/jpeg")
    upload_message = f"Image uploaded to gs://{your-image-bucket-name}/{filename}"
    print(upload_message)
    return upload_message, 200
    except Exception as e:
    error_message = f"Error during upload: {e}"
    print(error_message)
    return error_message, 500
    else:
    error_message = "Image generation failed."
    print(error_message)
    return error_message, 500


    I don't know what to try. All the information I find on this is talking about google cloud functions and it seems recently google changed the set up to use google cloud run functions instead and I do not get all the technicalities of that.

    Continue reading...

Compartilhe esta Página